sample_transaction.vb
Try
' SQLServerに接続する
Dim con As New SqlConnection(
"Data Source=hoge\SQLEXPRESS;" +
"Initial Catalog=hoge;" +
"Integrated Security=True")
Dim cmd As New SqlCommand
Dim sql As New StringBuilder
con.Open()
cmd.Connection = con
'トランザクション
Dim tran As SqlTransaction
tran = con.BeginTransaction
Try
sql.AppendLine("INSERT INTO dbo.EMPLOYEES ")
sql.AppendLine("( ")
sql.AppendLine(" id, name ")
sql.AppendLine(") VALUES ( ")
sql.AppendLine(" @id, @name ")
sql.AppendLine("); ")
cmd.CommandType = CommandType.Text
cmd.CommandText = sql.ToString()
For i As Integer = 0 To dt.Rows.Count - 1
cmd.Parameters.Clear()
cmd.Parameters.Add("@id", SqlDbType.Int).Value = dt.Rows(i).Item(0)
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = dt.Rows(i).Item(1)
'プロシージャの実行
cmd.Transaction = tran
cmd.ExecuteNonQuery()
Next i
'コミット
tran.Commit()
Catch ex As Exception
'ロールバック
tran.Rollback()
End Try
Catch ex As Exception
MsgBox(ex.ToString)
End Try