2011年3月3日 星期四

如何做資料庫交易(Transation)

這裡需要一個Button

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\temp\db1.mdb")
Dim cm As New Data.OleDb.OleDbCommand
Dim trans As Data.OleDb.OleDbTransaction
cm.Connection = cn
cm.CommandText = "Insert into test1 (t1,t2,t3) values (@val1,@val2,@val3)"
cm.Parameters.Add("val1", Data.OleDb.OleDbType.Decimal).Value = 4
cm.Parameters.Add("val2", Data.OleDb.OleDbType.Decimal).Value = 5
cm.Parameters.Add("val3", Data.OleDb.OleDbType.DBTimeStamp).Value = Date.Parse("2006/04/05")
cn.Open()
trans = cn.BeginTransaction '開始交易
Try
cm.Transaction = trans
cm.ExecuteNonQuery() '使用Parameter 的方式來更新資料
cm.CommandText = "Insert Into test1 (t1,t2,t3) values (44,55,#2006/04/05#)" '直接串成SQL語法更新
cm.ExecuteNonQuery()
trans.Commit() '完成時Commit
Catch ex As Exception
trans.Rollback() '失敗時Rollback
Finally
cn.Close()
End Try
End Sub

沒有留言:

張貼留言