批量导入数据到数据库
//connectionString 连接数据库字符串 TableName 需要导入的数据表名 dt 需要导入的DataTable
private bool SqlBulkCopyByDatatable(string connectionString, string TableName, System.Data.DataTable dt)
{
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString))
{
using (Sys tem.Data.SqlClient.SqlBulkCopy sqlbulkcopy = new System.Data.SqlClient.SqlBulkCopy(connectionString, System.Data.SqlClient.SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
sqlbulkcopy.DestinationTableName = TableName;
for (int i = 0; i < dt.Columns.Count; i++)
{
sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
}
sqlbulkcopy.WriteToServer(dt);
return true;
}
catch (System.Exception ex)
{
throw ex;
return false;
}
}
}
}