当前位置:Gxlcms > 数据库问题 > Sql Server海量数据插入

Sql Server海量数据插入

时间:2021-07-01 10:21:17 帮助过:14人阅读

<summary> /// 生成测试数据 /// </summary> private static void GenerateTestData() { string fileName = "sql"; int i = 1; while (i <= 500000) { string strInsert = string.Format("{0},‘test{0}‘,{0}|", i); File.AppendText(strInsert, fileName); i++; } } View Code

 

  第三步:封装出两个方法,分别用来执行批量插入和普通插入,具体代码如下:

技术分享
/// <summary>
        /// 批量插入测试
        /// </summary>
        private static void BulkInsertTest()
        {
            string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest\sql.txt";
            string strTableName = "Student";

            /* 每一个字段的信息以“,”分割 
            *每一条数据以“|”符号分隔
            * 每10万条数据一个事务*/
            string sql = string.Format("BULK INSERT {0} FROM ‘{1}‘ WITH (FIELDTERMINATOR = ‘,‘,ROWTERMINATOR =‘|‘,BATCHSIZE = 50000)", strTableName, strFilePath);
            DBHelper dbHelper = new DBHelper();
            dbHelper.Excute(sql);

        }

        /// <summary>
        /// 普通插入测试
        /// </summary>
        private static void CommonInsertTest()
        {
            int i = 1;
            while (i <= 500000)
            {
                string sqlInsert = string.Format("insert into Student1(id,Name,Age) values({0},‘test{0}‘,{0})", i);
                new DBHelper().Excute(sqlInsert);
                i++;
            }
        }
View Code

 

   第四步:Main主函数中调用批量插入和普通插入方法,并通过Stopwatch计算出执行时间,Pragram完整代码如下:

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QYH.BlukInsertTest.FileMange;
using QYH.BlukInsertTest.DataBase;
using System.Diagnostics;

namespace QYH.BlukInsertTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //用于生成海量数据
            //GenerateTestData();

            Stopwatch stopwatch = Stopwatch.StartNew();
            try
            {
                BulkInsertTest();
            }
            catch (Exception)
            {

                //throw;
            }

            stopwatch.Stop();
            string strResult = "批量插入耗时:" + stopwatch.ElapsedMilliseconds.ToString();

            Stopwatch stopwatch1 = Stopwatch.StartNew();
            CommonInsertTest();
            stopwatch1.Stop();
            string str1Result = "普通插入耗时:" + stopwatch1.ElapsedMilliseconds.ToString();

            string strTestResult = "result";
            File.WriteTextAsync(strResult + "\r\n" + str1Result, strTestResult);

            //Console.Read();
        }

        /// <summary>
        /// 批量插入测试
        /// </summary>
        private static void BulkInsertTest()
        {
            string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest\sql.txt";
            string strTableName = "Student";

            /* 每一个字段的信息以“,”分割 
            *每一条数据以“|”符号分隔
            * 每10万条数据一个事务*/
            string sql = string.Format("BULK INSERT {0} FROM ‘{1}‘ WITH (FIELDTERMINATOR = ‘,‘,ROWTERMINATOR =‘|‘,BATCHSIZE = 50000)", strTableName, strFilePath);
            DBHelper dbHelper = new DBHelper();
            dbHelper.Excute(sql);

        }

        /// <summary>
        /// 普通插入测试
        /// </summary>
        private static void CommonInsertTest()
        {
            int i = 1;
            while (i <= 500000)
            {
                string sqlInsert = string.Format("insert into Student1(id,Name,Age) values({0},‘test{0}‘,{0})", i);
                new DBHelper().Excute(sqlInsert);
                i++;
            }
        }

        /// <summary>
        /// 生成测试数据
        /// </summary>
        private static void GenerateTestData()
        {
            string fileName = "sql";

            int i = 1;
            while (i <= 500000)
            {
                string strInsert = string.Format("{0},‘test{0}‘,{0}|", i);
                File.AppendText(strInsert, fileName);
                i++;
            }
        }
    }
}
View Code

  示例中还用到两个辅助类,DBHelper.cs和File.cs,由于仅用于演示,所以写的非常简单,其中文件路径是写死的,可以替换成实际路径。

  DBHelper.cs  

技术分享
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QYH.BlukInsertTest.DataBase
{
    public class DBHelper
    {
        public string connectionString = "Server=.;Database=QYHDB;User ID=sa;Password=123456;Trusted_Connection=False;";

        public void Excute(string sql)
        {
            SqlConnection conn = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand();
            command.CommandTimeout = 0;
            command.Connection = conn;
            command.CommandText = sql;
            conn.Open();
            command.ExecuteNonQuery();
            conn.Close();
        }
    }
}
View Code

 

   File.cs

技术分享
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QYH.BlukInsertTest.FileMange
{
    public class File
    {
        public static string strFilePath = @"D:\学习\ASP.NET\QYH.BlukInsertTest";

        public static async void WriteTextAsync(string text, string fileName)
        {
            using (StreamWriter outputFile = new StreamWriter(strFilePath + @"\" + fileName + ".txt"))
            {
                await outputFile.WriteAsync(text);
            }
        }

        public static void AppendText(string text, string fileName)
        {
            // Append text to an existing file named "WriteLines.txt".
            using (StreamWriter outputFile = new StreamWriter(strFilePath + @"\" + fileName + ".txt",true))
            {
                outputFile.WriteLine(text);
            }
        }
    }
}
View Code

 

  

  一切准备就绪,开始运行,结果如下:

  技术分享

  其中单位为毫秒,从结果我们可以看出BULK INSER插入500000条数据还不需要3秒,而普通逐条插入却需要20多分钟

 

      

 

Sql Server海量数据插入

标签:.text   分隔符   多参数   asp   while   服务器   event   round   参数   

人气教程排行