[vb.net] transaction sql server
bonjour bonjour !
j'essaie de mettre en place une transaction... comme ceci :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| Dim oConnection As SqlClient.SqlConnection
Dim i As Integer
Try
oConnection.ConnectionString = oString
oConnection.Open()
For i = 0 To 2
'initilisation transaction
Dim Transac As SqlClient.SqlTransaction = oConnection.BeginTransaction
'creation commandes à éxécuter
Dim SQLTransac As SqlClient.SqlCommand = oConnection.CreateCommand
'commandes contrôlées par la transaction.
oCommand.Transaction = Transac
oCommand.CommandType = CommandType.Text
If i = 1 Then
oCommand.CommandText = "INSERT INTO test values"
Else
oCommand.CommandText = "INSERT INTO test(test_id) values (" & i & ")"
End If
Try
If Not (oCommand.ExecuteNonQuery = 0) Then
'enregistrement
Transac.Commit()
Else
'erreur annulation
Transac.Rollback()
MessageBox.Show("Erreur d'écriture dans la base de données")
End If
Catch ex As Exception
'annulation
Transac.Rollback()
MessageBox.Show("Erreur d'écriture dans la base de données: " + ex.Message)
End Try
Next
oCommand.Dispose()
oConnection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try |
j'ai mis volontairement une condition :
Code:
1 2 3 4 5
| If i = 1 Then
oCommand.CommandText = "INSERT INTO test values"
Else
oCommand.CommandText = "INSERT INTO test(test_id) values (" & i & ")"
End If |
pour faire planter une de mes requêtes et vérifier que ça annule bien les premières requêtes qui se sont éxecutées, mais ça n'annule rien du tout :?
une erreur dons mon code ?! :o merci !
Re: [vb.net] transaction sql server
ok :oops: :wink: mal lu de ma part excuses
Je verrai les choses plutôt ainsi alors
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
Imports System
Imports System.Data
Imports System.Data.SqlClient
'...
Const badInsert As String = "INSERT INTO test values"
Const insert As String = "INSERT INTO test(test_id) values(?)"
Dim oConnection As SqlConnection = Nothing
Dim SQLTransac As SqlCommand = Nothing
Dim Transac As SqlTransaction = Nothing
Dim i As Integer
Try
oConnection =New SqlConnection(oString)
oConnection.Open()
Transac = oConnection.BeginTransaction()
SQLTransac = oConnection.CreateCommand()
SQLTransac.Connection = oConnection
SQLTransac.Transaction = Transac
For i=0 to 2
If i = 1 Then: SQLTransac.CommandText = badInsert
Else : SQLTransac.CommandText = insert.Replace("?", i.ToString())
End If
SQLTransac.ExecuteNonQuery()
Next
Transac.Commit()
Catch e As Exception
Try
Transac.Rollback()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
MessageBox.Show(e.Message)
Finally
If Not(oConnection Is Nothing) _
AndAlso Not(oConnection.State = ConnectionState.Closed) Then
oConnection.Close()
End If
End Try |