测试 批量 插入 数据库

using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BigData
{
    class Program
    {
        static void Main(string[] args)
        {
            IDbConnection connection = new SqlConnection("data source=127.0.0.1;initial catalog=DBTest;persist security info=True;user id=sa;password=123456;");
            IDbConnection connection2 = new SqlConnection("data source=127.0.0.1;initial catalog=DBTest;persist security info=True;user id=sa;password=123456;");


            byte[] randomBytes = new byte[4];
            RNGCryptoServiceProvider rngServiceProvider = new RNGCryptoServiceProvider();//产生随机数

            //       System.Diagnostics.Stopwatch stopwatch = new Stopwatch();
            //       stopwatch.Start(); //  开始监视代码运行时间
            //       #region 方式1
            //       for (int i = 1568691; i < 1578691; i++)//100000000
            //       {
            //           rngServiceProvider.GetBytes(randomBytes);
            //           Int32 resultInt = BitConverter.ToInt32(randomBytes, 0);
            //           string sql = $@" INSERT INTO [dbo].[User]
            //      ([Name]
            //       ,[Num]
            //      ,[Time])
            //VALUES
            //      ('Name{i}'
            //       ,{resultInt}
            //      ,'{DateTime.Now}') ";
            //           var result = connection.Execute(sql,
            //                  new { });
            //       } 
            //       #endregion
            //       stopwatch.Stop(); //  停止监视
            //       TimeSpan timespan = stopwatch.Elapsed;  //获取当前实例测量得出的总时间
            //       Console.WriteLine("方式1代码执行时间:{0}(毫秒)", timespan.TotalMilliseconds);//总毫秒数


            System.Diagnostics.Stopwatch stopwatch2 = new Stopwatch();
            stopwatch2.Start(); //  开始监视代码运行时间
            #region 方式2

            StringBuilder sb = new StringBuilder();

            for (int i = 1588691; i < 1598691; i++)//100000000
            {
                rngServiceProvider.GetBytes(randomBytes);
                Int32 resultInt = BitConverter.ToInt32(randomBytes, 0);

                sb.AppendLine($@" INSERT INTO [dbo].[User]
           ([Name]
            ,[Num]
           ,[Time])
     VALUES
           ('Name{i}'
            ,{resultInt}
           ,'{DateTime.Now}') ");

            }
            var result2 = connection.Execute(sb.ToString(),
                               new { });


            #endregion
            stopwatch2.Stop(); //  停止监视
            TimeSpan timespan2 = stopwatch2.Elapsed;  //获取当前实例测量得出的总时间
            Console.WriteLine("方式2代码执行时间:{0}(毫秒)", timespan2.TotalMilliseconds);//总毫秒数
                                                                                // 1万行数据
                                                                                //方式1代码执行时间:80770.9122(毫秒)
                                                                                //方式2代码执行时间:22732.9235(毫秒)
                                                                                //2 万行 数据库执行超时
                                                                                //10 万行 数据库执行超时


            System.Diagnostics.Stopwatch stopwatch3 = new Stopwatch();
            stopwatch3.Start(); //  开始监视代码运行时间

            #region 方式3
            List<Task> tasks = new List<Task>();
            tasks.Add(Task.Run(() =>
            {
                InsertFun(connection, rngServiceProvider,
 randomBytes, 1598691, 1603691);
            }));
            tasks.Add(Task.Run(() =>
            {
                InsertFun(connection2, rngServiceProvider,
randomBytes, 1603691, 1608691);
            }));
            Task.WaitAll();
            #endregion

            stopwatch3.Stop(); //  停止监视
            TimeSpan timespan3 = stopwatch3.Elapsed;  //获取当前实例测量得出的总时间
            Console.WriteLine("方式3代码执行时间:{0}(毫秒)", timespan3.TotalMilliseconds);//总毫秒数
            // 1万条数据测试
            //方式2代码执行时间:28438.1286(毫秒)
            //方式3代码执行时间:41.3877(毫秒)

            Console.Read();
        }





        static void InsertFun(IDbConnection connection, RNGCryptoServiceProvider rngServiceProvider,
            byte[] randomBytes, int start, int end)
        {
            #region 方式3

            StringBuilder sb3 = new StringBuilder();

            for (int i = start; i < end; i++)//100000000
            {
                rngServiceProvider.GetBytes(randomBytes);
                Int32 resultInt = BitConverter.ToInt32(randomBytes, 0);

                sb3.AppendLine($@" INSERT INTO [dbo].[User]
           ([Name]
            ,[Num]
           ,[Time])
     VALUES
           ('Name{i}'
            ,{resultInt}
           ,'{DateTime.Now}') ");

            }
            var result3 = connection.Execute(sb3.ToString(),
                               new { });


            #endregion

        }
    }




    public class Random
    {
        public int Get(System.Security.Cryptography.RNGCryptoServiceProvider rng)
        {
            //这样产生0 ~ 100的强随机数(含100)
            int max = 100;
            int rnd = int.MinValue;
            decimal _base = (decimal)long.MaxValue;
            byte[] rndSeries = new byte[8];

            //但是要注意别扔到循环里去,实例化RNG对象可是很消耗资源的
            //System.Security.Cryptography.RNGCryptoServiceProvider rng
            //    = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(rndSeries);
            //不含100需去掉+1 
            //这个rnd就是你要的随机数,
            return rnd = (int)(Math.Abs(BitConverter.ToInt64(rndSeries, 0)) / _base * (max + 1));



        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当涉及到批量插入数据库时,以下是一些优化策略可以考虑: 1. 使用事务:将插入操作包装在事务中,这样可以减少每个插入操作的开销,并提高整体性能。通过将所有插入操作作为一个原子操作提交,可以减少数据库的日志记录和索引更新次数。 2. 批量大小:确定每个批量插入的大小是一个重要的考虑因素。如果批量太小,将导致频繁的数据库连接和提交操作,增加了开销。相反,如果批量太大,可能会占用过多的内存和导致长时间的事务。通过进行实际测试,找到一个适合的批量大小是很重要的。 3. 批量插入语句:使用数据库提供的批量插入语句,如MySQL的`INSERT INTO ... VALUES (),(),()...`或PostgreSQL的`INSERT INTO ... SELECT UNION ALL SELECT ...`。这些语句可以一次性插入多行数据,减少了通信开销和减少了网络往返次数。 4. 禁用索引和约束:在执行批量插入操作之前,可以考虑禁用表上的索引和约束。这样做可以减少每个插入操作的开销,并在插入完成后再重新启用索引和约束。 5. 使用连接池:在应用程序级别使用连接池可以提高数据库连接的性能和重用。连接池可以管理和维护一组预先建立的数据库连接,避免频繁地创建和销毁连接。 6. 批量插入并行化:如果数据量非常大,可以考虑将批量插入操作并行化处理。将数据分割成多个子批次,并使用多个线程或进程同时插入。这样可以利用多核处理器和并行计算的优势来提高插入性能。 请注意,以上优化策略的适用性可能会因数据库类型、硬件配置和具体业务需求而有所不同。在实际应用中,根据具体情况进行测试和调整是至关重要的。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值