[英]Multiple insert into SQL Server 2008 via Ado.Net 3.5 and C#
I have a collection of data. 我有数据收集。 I need to insert these records into SQL Server 2008. I also need to maintain transaction, so that if one insert fails, I need to rollback all the changes done. 我需要将这些记录插入SQL Server2008。我还需要维护事务,因此,如果一次插入失败,则需要回滚所有已完成的更改。
Can some one suggest a best way to do this? 有人可以建议这样做的最佳方法吗? I use .Net 3.5. 我使用.Net 3.5。
You need to create a transaction using your SqlConnection
object's BeginTransaction method. 您需要使用SqlConnection
对象的BeginTransaction方法创建事务。 This will return an SqlTransaction
object that you need to keep track of. 这将返回您需要跟踪的SqlTransaction
对象。
When all of your items have been successfully inserted into the database, you will call Commit on the transaction object. 将所有项目成功插入数据库后,您将在事务对象上调用Commit。
If an exception is encountered during your processing, you will need to call Rollback on the transaction object. 如果在处理期间遇到异常,则需要在事务对象上调用回滚。
Roughly speaking, the code is: 大致来说,代码是:
SqlConnection conn;
// Create and open your connection here
SqlTransaction trans = conn.BeginTransaction();
try {
// Perform your inserts
trans.Commit();
} catch(Exception ex) {
trans.Rollback();
// Report the exception
}
阅读有关TransactionScope和System.Transactions的全部信息。
Depending of wheather you are using ADO.NET/plain SQL you can use bulk insert, or, if you are using Linq-to-SQL you can try using LINQ Entity Data Reader to insert large amounts of data at once. 根据使用的是ADO.NET/普通SQL,可以使用批量插入,或者,如果使用的是Linq-to-SQL,则可以尝试使用LINQ实体数据读取器一次插入大量数据。
By using bulk insert each batch is copied to the server as one transaction. 通过使用批量插入,每个批次将作为一个事务复制到服务器。 If this fails, SQL Server commits or rolls back the transaction for every batch. 如果失败,SQL Server将为每个批处理提交或回滚事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.