1.簡介
1.MSDN
核心方法:SqlBulkCopy.WriteToServer
將所有行從數據源復制到 SqlBulkCopy 對象的 DestinationTableName 屬性指定的目標表中.
2.一句話介紹
將DataTable或DataRow中的數據直接復制到數據庫中指定的表中
3.注意事項
- 表名、列名對大小寫敏感
- DataTable的架構必須和目標表保持一致(最常出的錯誤就是列順序不一致)
- DataTable中int類型的字段如果為NULL,必須對其賦值為 DBNull.Value
- SqlBulkCopy遇到重復字段只會直接報錯,然后默認回滾所有復制操作即復制到一半出錯了,那整個前面復制也都放棄掉
2.示例
1.使用SqlBulkCopy
調用格式
SqlBulkCopyByDatatable(SQLAss.GetConnString(),"PartList", excelDt);
SQLHelper類
public SQLHelper()
{
//DatabaseTest 引用自web.config connectionStrings中
string strconn = ConfigurationManager.ConnectionStrings["SQLAss"].ConnectionString;
conn = new SqlConnection(strconn);
}
public string GetConnString()
{
return conn.ConnectionString;
}
Web.config
注意必須要有:Persist Security Info=True
<configuration>
<connectionStrings>
<add name="SQLAss" connectionString="Persist Security Info=True; SERVER=10.100.10.100;DATABASE=DBName;UID=userId;PWD=password;Connect Timeout=2880"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
SqlBulkCopy
public static void SqlBulkCopyByDatatable(string ConnectionString, string TableName, DataTable Dt)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlBulkCopy sqlbulkcopy =new SqlBulkCopy(ConnectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
sqlbulkcopy.BulkCopyTimeout = 5000;//指定超時時間 以秒為單位 默認超時時間是30秒,設置為0即不限時間
sqlbulkcopy.DestinationTableName = TableName;//目標數據庫表名
for (int i = 0; i < Dt.Columns.Count; i++)
{
//映射字段名 DataTable列名 ,數據庫對應列名
sqlbulkcopy.ColumnMappings.Add(Dt.Columns[i].ColumnName, Dt.Columns[i].ColumnName);
}
/*
//額外,可不寫:設置一次性處理的行數。這個行數處理完后,會激發SqlRowsCopied()方法。默認為1
//這個可以用來提示用戶S,qlBulkCopy的進度
sqlbulkcopy.NotifyAfter = 1;
//設置激發的SqlRowsCopied()方法,這里為sqlbulkcopy_SqlRowsCopied
sqlbulkcopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(bulkCopy_SqlRowsCopied);
*/
sqlbulkcopy.WriteToServer(Dt);//將數據源拷備到目標數據庫
}
catch (System.Exception e)
{
// throw e;
string eMessage=e.Message.ToString();
int indexLeft=eMessage.IndexOf("重復鍵值為 (")+7;
int indexRight=eMessage.IndexOf(")。");
int strLength = indexRight- indexLeft;
if (indexLeft!= -1)
{
throw new Exception("批量導入失敗,存在重復記錄:"+eMessage.Substring(indexLeft,strLength));
}
else
{
throw e;
}
}
finally
{
conn.Close();
}
}
}
}
2.重復字段處理
直接報錯或參考yudehui網友采用遞歸思想的跳過重復行繼續復制