最近一直在到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(); } }
1 public DataTable GetTableSchema() 2 { 3 DataTable dt = new DataTable(); 4 dt.Columns.AddRange(new DataColumn[]{ 5 new DataColumn("studentID",typeof(Guid)), 6 new DataColumn("studentCode",typeof(string)), 7 new DataColumn("studentName",typeof(string)), 8 new DataColumn("schoolCode",typeof(string)), 9 new DataColumn("gradeCode",typeof(string)), 10 new DataColumn("classesCode",typeof(string)), 11 new DataColumn("period",typeof(string)), 12 new DataColumn("nationChineseIdentifyCode",typeof(string)), 13 new DataColumn("scienceOrArtIdentifyCode",typeof(string)), 14 //new DataColumn("examRoomCode",typeof(Guid)), 15 //new DataColumn("seatNumber",typeof(int)) 16 });//数据库表结构 17 return dt; 18 }