最近一直在到excel导入,无意中发现Bulk Insert 批量导入,于是研究了一下,在测试的时候一直有问题,然后找度娘帮忙,说新增DataTable数据结构的时候,每个列要与数据库设计时字段对应,然后试了一下,OK了。

写这个主要是记录遇到的问题,下次再遇到的时候,能及时解决,也希望能帮助更多的朋友。

public static void BulkToDB(DataTable dt)
{
// SqlConnection sqlConn = new SqlConnection("Data Source=192.168.6.162 ;Initial Catalog=DBMarkingSchool;User ID=sa;Password=123456");
SqlConnection sqlConn = new SqlConnection(dbConnectionString);
SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn);
bulkCopy.DestinationTableName = "Students";//数据库表名
bulkCopy.BatchSize = dt.Rows.Count;
try
{
sqlConn.Open();
if (dt != null && dt.Rows.Count != 0)
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
//new AppException("批量生成直播室账号异常", ex);
}
finally
{
sqlConn.Close();
if (bulkCopy != null)
bulkCopy.Close();
}
}

  

  public DataTable GetTableSchema()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]{
new DataColumn("studentID",typeof(Guid)),
new DataColumn("studentCode",typeof(string)),
new DataColumn("studentName",typeof(string)),
new DataColumn("schoolCode",typeof(string)),
new DataColumn("gradeCode",typeof(string)),
new DataColumn("classesCode",typeof(string)),
new DataColumn("period",typeof(string)),
new DataColumn("nationChineseIdentifyCode",typeof(string)),
new DataColumn("scienceOrArtIdentifyCode",typeof(string)),
//new DataColumn("examRoomCode",typeof(Guid)),
//new DataColumn("seatNumber",typeof(int))
});//数据库表结构
return dt;
}
05-08 08:39