Use C# for batch insertion of SqlServer

        In many cases, we will perform a batch insertion operation, such as reading Excel data and batch inserting into the database. At this time, it is impossible to traverse one by one and insert one by one. SqlBulkCopy in C# provides the function of batch insertion. To use SqlBulkCopy for batch insertion, you need to create a table in the database. When inserting, you mainly use a DataTable to transfer values. The columns to be inserted in the DataTable need to correspond to the corresponding columns in the database. Here is mainly about how to use, the code is as follows:

try
{
    //这里模拟一个DataTable数据,批量插入主要插入的就是一个DataTable
    DataTable dt = new DataTable();
    dt.Columns.Add("LOGINNAME");
    dt.Columns.Add("USERNAME");
    //给DataTable赋值
    for(int i = 0;i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["LOGINNAME"] = i;
        row["USERNAME"] = i;
        dt.rows.Add(row);
    }
    using(SqlConnection cn = new SqlConnection("Data Source=xx.xxx.xx.xxx;Initial Catalog = XXXX;Integrated Security = SSPI;"))
    {
        cn.Open();
        SqlBulkCopy sqlBulkCopy = new SqlBulkCopy();
        //这里对应的是数据库里面的表的表名
        sqlBulkCopy.DestinationTableName = "TEST";
        //前面的参数是对应插入的DataTable的字段,后面是对应的数据库的表的字段,将要插入的DataTable与要对应的数据库字段一一对应即可
        sqlBulkCopy.ColumnMappings.Add("LOGINNAME","LOGINNAME");
        sqlBulkCopy.ColumnMappings.Add("USERNAME","USERNAME");
        //进行数据的批量插入操作
        sqlBulkCopy.WriteToServer(dt);
        
    }
}
catch(Exception ex)
{
    Console.WriteLine(ex);
}

       

Guess you like

Origin blog.csdn.net/qq_41061437/article/details/105521919