コード例 #1
0
 static void Main(string[] args)
 {
     //自动 open
     using (var con = new MySqlConnection("server=localhost;port=3306;uid=root;pwd=admin;database=test"))
     {
         var count1 = con.Count <MsgModel2>();
         var msgs2  = con.Query <MsgModel2>(m => m.Id == 10);
         var msg    = msgs2.FirstOrDefault();
         if (msg != null)
         {
             msg.PhoneNum = "sdfsdfdfsdf";
             con.Add(msg);
             msg.PhoneNum = "13344444444";
             con.Update(msg);
         }
         con.Delete <MsgModel2>(m => m.Id == 10);
         //事务 成功时返回 true, 失败时 返回 false 会调用回滚
         con.Transaction(cmd =>
         {
             var count = cmd.Delete <MsgModel2>(m => m.Id == 10);
             if (count == 1)
             {
                 return(true);
             }
             return(false);
         });
     }
     Console.ReadLine();
 }
コード例 #2
0
 private static void SetCount()
 {
     using (var con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnString"].ToString()))
     {
         TotalPhotoCount = con.Count <PhotoInfo>();
     }
 }
コード例 #3
0
ファイル: DatabaseService.cs プロジェクト: dex252/GuestBook
        public long?Count <T>()
        {
            using MySqlConnection conn = GetConnection();

            conn.Open();

            var count = conn.Count <T>();

            return(count);
        }
コード例 #4
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void ThrowExceptionOnMySqlConnectionCountWithHints()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                connection.Count <CompleteTable>((object)null,
                                                 hints: "WhatEver");
            }
        }
コード例 #5
0
ファイル: TransactionTests.cs プロジェクト: sellig/RepoDb
 public void TestSqlTransactionForCount()
 {
     using (var connection = new MySqlConnection(Database.ConnectionString))
     {
         // Prepare
         using (var transaction = connection.EnsureOpen().BeginTransaction())
         {
             // Act
             connection.Count <CompleteTable>(it => it.Id != 0, transaction: transaction);
         }
     }
 }
コード例 #6
0
        public void BulkInsertZeroEntries()
        {
            var dtos = new LocationDto[0];

            using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySql"].ConnectionString))
            {
                conn.Open();
                conn.BulkInsert(dtos);

                Assert.That(conn.Count <LocationDto>(), Is.EqualTo(0));
            }
        }
コード例 #7
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void ThrowExceptionOnMySqlConnectionCountViaTableNameWithHints()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                connection.Count(ClassMappedNameCache.Get <CompleteTable>(),
                                 (object)null,
                                 hints: "WhatEver");
            }
        }
コード例 #8
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void TestMySqlConnectionCountViaQueryField()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                var result = connection.Count <CompleteTable>(new QueryField("Id", tables.First().Id));

                // Assert
                Assert.AreEqual(tables.Where(e => e.Id == tables.First().Id).Count(), result);
            }
        }
コード例 #9
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void TestMySqlConnectionCountWithoutExpression()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                var result = connection.Count <CompleteTable>((object)null);

                // Assert
                Assert.AreEqual(tables.Count(), result);
            }
        }
コード例 #10
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void TestMySqlConnectionCountViaExpression()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);
            var ids    = new[] { tables.First().Id, tables.Last().Id };

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                var result = connection.Count <CompleteTable>(e => ids.Contains(e.Id));

                // Assert
                Assert.AreEqual(tables.Where(e => ids.Contains(e.Id)).Count(), result);
            }
        }
コード例 #11
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void TestMySqlConnectionCountViaTableNameViaDynamic()
        {
            // Setup
            var tables = Database.CreateCompleteTables(10);

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                var result = connection.Count(ClassMappedNameCache.Get <CompleteTable>(),
                                              new { tables.First().Id });

                // Assert
                Assert.AreEqual(tables.Where(e => e.Id == tables.First().Id).Count(), result);
            }
        }
コード例 #12
0
ファイル: CountTest.cs プロジェクト: say25/RepoDb
        public void TestMySqlConnectionCountViaQueryFields()
        {
            // Setup
            var tables      = Database.CreateCompleteTables(10);
            var queryFields = new[]
            {
                new QueryField("Id", Operation.GreaterThan, tables.First().Id),
                new QueryField("Id", Operation.LessThan, tables.Last().Id)
            };

            using (var connection = new MySqlConnection(Database.ConnectionString))
            {
                // Act
                var result = connection.Count <CompleteTable>(queryFields);

                // Assert
                Assert.AreEqual(tables.Where(e => e.Id > tables.First().Id&& e.Id < tables.Last().Id).Count(), result);
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: fengrui358/Labs
        static void Main(string[] args)
        {
            OrmConfiguration.DefaultDialect = SqlDialect.MySql;

            var random = new Random().Next(1, 10000);

            dbName = string.Format("testdb{0}", random);

            using (
                var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString)
                )
            {
                //创建数据库
                var createDbSql = string.Format("CREATE DATABASE IF NOT EXISTS `{0}`;", dbName);
                con.Execute(createDbSql);
                con.Open();

                con.ChangeDatabase(dbName);

                //创建表
                var sql = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "user.sql.txt"));

                con.Execute(sql);
                con.Close();
            }


            using (
                var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString)
                )
            {
                con.Open();

                con.ChangeDatabase(dbName);

                con.Close();
            }

            Console.WriteLine("准备插入数据");

            var becaonFlag = new Random(DateTime.Now.Millisecond).Next(1, Total);
            var tempUsers  = new User[Total];

            for (int i = 0; i < Total; i++)
            {
                if (becaonFlag == i)
                {
                    var user = new User {
                        OpenId = beacon.ToString()
                    };
                    tempUsers[i] = user;
                }
                else
                {
                    tempUsers[i] = new User();
                }
            }

            BulkInsertAsync(tempUsers);

            var repeatUser = new User {
                OpenId = beacon.ToString()
            };

            Console.WriteLine("开始测试抛异常");

            var sw = Stopwatch.StartNew();

            try
            {
                using (
                    var con =
                        new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString)
                    )
                {
                    con.Open();
                    con.ChangeDatabase(dbName);

                    try
                    {
                        con.Insert(repeatUser);
                    }
                    finally
                    {
                        con.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                sw.Stop();

                Console.WriteLine(ex);
                Console.WriteLine($"抛异常耗时:{sw.ElapsedMilliseconds}");
            }

            sw.Restart();

            using (
                var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString)
                )
            {
                con.Open();
                con.ChangeDatabase(dbName);

                var count = con.Count <User>(
                    statement =>
                    statement.Where($"{nameof(User.OpenId):C}=@OpenIdParm")
                    .WithParameters(new { OpenIdParm = repeatUser.OpenId }));

                sw.Stop();
                if (count > 0)
                {
                    Console.WriteLine($"发现重复数据,耗时:{sw.ElapsedMilliseconds}");
                }

                con.Close();
            }

            Console.WriteLine("测试完毕,点击任意键删除测试数据库");

            Console.ReadKey();

            using (
                var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnString"].ConnectionString)
                )
            {
                //删除数据库
                con.Execute(string.Format("DROP DATABASE IF EXISTS `{0}`;", dbName));
            }
        }
コード例 #14
0
        private static void TimerHandler(object obj)
        {
            try
            {
                var contentCache = _contentCache.Values.ToList();
                _contentCache.Clear();

                if (contentCache.Any())
                {
                    var repetitions = new List <PhotoInfo>();

                    foreach (var photoInfo in contentCache)
                    {
                        using (
                            var con =
                                new MySqlConnection(
                                    WebConfigurationManager.ConnectionStrings["MySqlConnString"].ToString()))
                        {
                            var count =
                                con.Count <PhotoInfo>(
                                    statement =>
                                    statement.Where($"{nameof(PhotoInfo.Md5):C}=@Md5")
                                    .WithParameters(new { Md5 = photoInfo.Md5 }));

                            if (count > 0)
                            {
                                repetitions.Add(photoInfo);
                            }
                        }
                    }

                    //删除重复
                    foreach (var photoInfo in repetitions)
                    {
                        contentCache.Remove(photoInfo);
                        DeleteContent(photoInfo);
                    }

                    using (var con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnString"].ToString()))
                    {
                        IDbTransaction transaction = null;

                        try
                        {
                            con.Open();
                            transaction = con.BeginTransaction();

                            foreach (var photoInfo in contentCache)
                            {
                                con.Insert(photoInfo);
                            }

                            transaction.Commit();
                        }
                        catch (Exception exception)
                        {
                            LogManager.GetCurrentClassLogger().Error(exception);
                            transaction.Rollback();
                        }
                        finally
                        {
                            con.Close();
                        }
                    }
                }

                SetCount();
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex);
            }
            finally
            {
                Timer.Change(CacheHandleInterval, Timeout.InfiniteTimeSpan);
            }
        }