複製代碼 代碼如下:using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
string connectionString = "Data Source=HG-J3EJJ9LSW5PY;Initial Catalog=Test;User ID=sa;password=hg";
DataTable dataTable = sql_.select_datagrid(" select a from large where 1=0 ").Tables[0];
string passportKey;
for (int i = 0; i < 100000; i++)
{
passportKey = Guid.NewGuid().ToString();
DataRow dataRow = dataTable.NewRow();
dataRow[0] = passportKey;
dataTable.Rows.Add(dataRow);
}
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlTransaction sqltran = sqlConnection.BeginTransaction();
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection, SqlBulkCopyOptions.KeepIdentity, sqltran);
sqlBulkCopy.DestinationTableName = "large";
sqlBulkCopy.BatchSize = dataTable.Rows.Count;
if (dataTable != null && dataTable.Rows.Count != 0)
{
sqlBulkCopy.WriteToServer(dataTable);
}
sqlBulkCopy.Close();
sqltran.Rollback();
sqlConnection.Close();
註解: <1> sqlBulkCopy.DestinationTableName = "large"; large 指的是目標表的名稱
<2> DataTable 的結構要和資料庫中的表的結構相同
(DataTable的列不能多於資料庫裡面的)
(DataTable的列可以少於資料庫裡面的 如果資料庫這一列有預設值的話)
<3> 這裡面 我使用了事務 您在使用的時候 也可以不用事務