我有一个vb.net网络应用程序,我将SQL连接和事务传递给将单个记录写入数据库的方法。
我想为每个写入的记录启动并提交一个事务,但是在循环完成之前使用相同的sql连接。
我看到的一种方法是使用using语句,但它对我不起作用。第一次运行并在第二次出错时提交了事务已经提交
Using sqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
sqlConnection.Open()
Using transaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
For Each user In users
Try
myDataWriteMethod(user, conn, tr)
Catch ex As Exception
tranaction.rollback()
End Try
transaction.commit()
Next
End Using
End Using
答案 0 :(得分:1)
看起来好像是在for循环的每一步提交或回滚事务。您可能需要(1)为每个用户开始一个新的交易,例如,
Using sqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
sqlConnection.Open()
For Each user In users
Using transaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
...
或(2)仅在最后提交或回滚事务,例如
Using sqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
sqlConnection.Open()
Using transaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
Try
For Each user In users
myDataWriteMethod(user, conn, tr)
Next
Catch ex As Exception
tranaction.rollback()
End Try
transaction.commit()
End Using
End Using
请注意,我不是VB.NET程序员,因此我的语法可能有误。
答案 1 :(得分:1)
这应该做你想要的。
Using sqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
sqlConnection.Open()
For Each user In users
Using transaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
Try
myDataWriteMethod(user, conn, tr)
transaction.Commit()
Catch ex As Exception
transaction.Rollback()
End Try
End Using
Next
End Using