我正在尝试将DataTable
复制到Sql Server上的目标表中。我使用以下代码。我知道bulkCopy.WriteToServer()
是一个原子(全有或全无)功能。但是当没有任何东西被复制时,我想知道!
try
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn.ConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.UseInternalTransaction))
{
bulkCopy.DestinationTableName = "MyDestinationTable";
bulkCopy.WriteToServer(dt);
convertSuccess = true;
}
}
catch
{
convertSuccess = false;
}
我已经看到没有任何内容被复制到“MyDestinationTable”但我没有意识到它的情况,因为我的convertSuccess
标志返回true
。有没有办法知道bulkCopy是否完成了它的工作?
答案 0 :(得分:1)
您可以指定 NotifyAfter 属性,然后在x行数后处理 SqlRowsCopied 事件。
static void Main() {
try {
using(SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn.ConnectionString, SqlBulkCopyOptions.KeepIdentity | SqlBulkCopyOptions.UseInternalTransaction)) {
//Event handling
bulkCopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
bulkCopy.NotifyAfter = 50; //Put your rowcount here
bulkCopy.DestinationTableName = "MyDestinationTable";
bulkCopy.WriteToServer(dt);
convertSuccess = true;
}
} catch {
convertSuccess = false;
}
}
private static void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e) {
Console.WriteLine("Copied {0} so far...", e.RowsCopied);
}