SqlBulkCopy
批量插入数据
新建一个table
DataTable table = new DataTable(); //声明表(该表存于本地服务器端,输入插入该表之后,再将这张表插入数据库) table.Columns.Add("Id"); table.Columns.Add("Column1"); table.Columns.Add("Column2"); 。。。。。。。。
从其他地方读取数据比如excel表格,txt等
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"文件地址"))
{ // 从文件读取并显示行,直到文件的末尾 while (!string.IsNullOrEmpty(line = sr.ReadLine())) { string[] items = line.Split(';'); var column1= items[0]); var column2 = items[1]); var column3 = ipitems[2]; DataRow row = table.NewRow(); row["Id"]=index; row["Column1"] = column1; row["Column2"] = column2 ; row["Column3"] = column3; //根据数据库表设计改变类型 table.Rows.Add(row); //查看索引值 System.Diagnostics.Debug.WriteLine(index); index++; }
using (SqlBulkCopy buckCopy = new SqlBulkCopy(dbHelperSQLP.connectionString))
{
buckCopy.BatchSize = 1000;
buckCopy.DestinationTableName = "数据库中的表名";
buckCopy.ColumnMappings.Add("Id", "Id");
buckCopy.ColumnMappings.Add("Column1", "Column1");
buckCopy.ColumnMappings.Add("Column2", "Column2");
buckCopy.ColumnMappings.Add("Column3", "Column3");
buckCopy.WriteToServer(table);
}
}