准备一个应用程序,该应用程序将由本地网络上的本地SQL Server在办公室中的大约40个用户使用。在VB.NET中开发的应用程序。我已经阅读了一些文档,但希望直接从您这方面获得有关数据访问的一些知识。
这是一个Winforms应用程序,我想知道我使用的事务是否足以保护数据,例如当一个用户使用某些数据而另一个用户同时更改它时,事务是否会保护它?有人可以简要解释一下它是怎么回事吗?
我在我的应用程序中使用的SQL事务的示例
touchesEnded
答案 0 :(得分:1)
根据您的商业规则,有两个版本 A)所有插入成功或全部失败。
Dim result As Boolean = True
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(String))'.ToString()'no need. It is already **String**
Using connection As New SqlConnection(strcon)
''//--Following 2 lines are OK
''//--Using cmd As New SqlCommand("INSERT INTO T_Sentence_SubSec_SecKatSubKat_SubSubKat (FK_Sentence_ID, FK_SubSec_SecKatSubKat_SubSubKat) VALUES (@FK_Sentence_ID, @FK_SubSec_SecKatSubKat_SubSubKat)", connection)
''//--cmd.CommandType = CommandType.Text
''//--but these two are better
Using cmd As New SqlCommand("dbo.T_Sentence_SubSec_SecKatSubKat_SubSubKat_ins ", connection)
''//-- Insert aricle to Articles table (T_Artikel) and get inserted
''//--row id to use it in other queries
cmd.CommandType = CommandType.StoredProcedure
''//-- Open generall connection for all the queries
''//--open connection in try block
''//--connection.Open()
''//-- Make the transaction.
''//--Dim transaction As SqlTransaction
''//--transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
Try
connection.Open()
cmd.Transaction = connection.BeginTransaction()
cmd.Parameters.Add("@FK_Sentence_ID", SqlDbType.Int) ''//--or whatever
cmd.Parameters.Add("@FK_SubSec_SecKatSubKat_SubSubKat", SqlDbType.Int)
For Each sentId In pSentsId
cmd.Parameters("@FK_Sentence_ID").Value = sentId
cmd.Parameters("@FK_SubSec_SecKatSubKat_SubSubKat").Value = SubSec_SecKatSubKat_SubSubKat
cmd.ExecuteNonQuery() ''//--returns rows affected. We do not use result
Next
''//--everything is OK
cmd.Transaction.Commit()
Catch ex as SqlException
result = False
''//--SqlException is more informative for this case
If cmd.Transaction IsNot Nothing
cmd.Transaction.Rollback
''//--extra try...catch if you wish
End If
Catch ex As Exception
result = False
''//-- Roll the transaction back.
Try
cmd.Transaction.Rollback()
Catch ex2 As Exception
''// This catch block will handle any errors that may have occurred
''// on the server that would cause the rollback to fail, such as
''// a closed connection.
''//Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
''//Console.WriteLine(" Message: {0}", ex2.Message)
End Try
Finally
If connection.State <> Closed
connection.Close()
End If
End Try
End Using''//cmd
End Using''//connection
Return result
B)每个插入物都是独立的。不要使用整体交易。在try...catch
循环内添加for
。