Preparing an application which will be used by around 40 users in office with local SQL Server at local network. Application developed in VB.NET. I already read some documentation but would like to get some knowledge directly from your side about access to data.
This is a Winforms app and I wonder whether transactions I am using will be just enough to protect data e.g when one user uses some data and other one will change it in same time, does transaction would protect it? Can someone explain me briefly how it is?
Example of SQL transaction I use in my application
Dim result As Boolean = True
Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(String)).ToString()
Using connection As New SqlConnection(strcon)
'-- Open generall connection for all the queries
connection.Open()
'-- Make the transaction.
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
Try
For Each sentId In pSentsId
'-- Insert aricle to Article's table (T_Artikel) and get inserted row id to use it in other queries
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
cmd.Connection = connection
cmd.Transaction = transaction
cmd.Parameters.AddWithValue("@FK_Sentence_ID", sentId)
cmd.Parameters.AddWithValue("@FK_SubSec_SecKatSubKat_SubSubKat", SubSec_SecKatSubKat_SubSubKat)
cmd.ExecuteScalar()
End Using
Next
transaction.Commit()
Catch ex As Exception
result = False
'-- Roll the transaction back.
Try
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
End Try
End Using
Return result
SqlCommandin each loop. This is bad practice. CreateSqlCommandonce and add parameters outside the loop. Set parameter values andExecuteNonQueryin the loop. CatchSqlExceptionfirst.SqlCommandin each loop. See my previous comment. No need to setIsolationLevel.ReadCommitted; this is default value. Depending on your business rules you can commit / rollback each insert or the whole group. AddFinallywhere you close connection.