sql server中批量插入與更新兩種解決方案分享(asp.net)_實用技巧

來源:互聯網
上載者:User
若只是需要大批量插入資料使用bcp是最好的,若同時需要插入、刪除、更建立議使用SqlDataAdapter我測試過有很高的效率,一般情況下這兩種就滿足需求了
bcp方式
複製代碼 代碼如下:

/// <summary>
/// 大批量插入資料(2000每批次)
/// 已採用整體事物控制
/// </summary>
/// <param name="connString">資料庫連結字串</param>
/// <param name="tableName">資料庫伺服器上目標表名</param>
/// <param name="dt">含有和目標資料庫表結構完全一致(所包含的欄位名完全一致即可)的DataTable</param>
public static void BulkCopy(string connString, string tableName, DataTable dt)
{
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlTransaction transaction = conn.BeginTransaction())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, transaction))
{
bulkCopy.BatchSize = 2000;
bulkCopy.BulkCopyTimeout = _CommandTimeOut;
bulkCopy.DestinationTableName = tableName;
try
{
foreach (DataColumn col in dt.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
bulkCopy.WriteToServer(dt);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
finally
{
conn.Close();
}
}
}
}
}

SqlDataAdapter
複製代碼 代碼如下:

/// <summary>
/// 批次更新資料(每批次5000)
/// </summary>
/// <param name="connString">資料庫連結字串</param>
/// <param name="table"></param>
public static void Update(string connString, DataTable table)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = conn.CreateCommand();
comm.CommandTimeout = _CommandTimeOut;
comm.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(comm);
SqlCommandBuilder commandBulider = new SqlCommandBuilder(adapter);
commandBulider.ConflictOption = ConflictOption.OverwriteChanges;
try
{
conn.Open();
//設定批次更新的每次處理條數
adapter.UpdateBatchSize = 5000;
adapter.SelectCommand.Transaction = conn.BeginTransaction();/////////////////開始事務
if (table.ExtendedProperties["SQL"] != null)
{
adapter.SelectCommand.CommandText = table.ExtendedProperties["SQL"].ToString();
}
adapter.Update(table);
adapter.SelectCommand.Transaction.Commit();/////提交事務
}
catch (Exception ex)
{
if (adapter.SelectCommand != null && adapter.SelectCommand.Transaction != null)
{
adapter.SelectCommand.Transaction.Rollback();
}
throw ex;
}
finally
{
conn.Close();
conn.Dispose();
}
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.