docmd.runsql 語句執行的操作查詢如何回滾?
2024-07-21 02:34:34
供稿:網友
問題:
docmd.runsql 語句執行的操作查詢如何回滾?
回答:
希望通過Docmd.RUNSQL實現事務的回滾(RollBack)操作
很遺憾的說,access無法法通過Docmd.RUNSQL來實現事務的回觥4蠹乙殘磣⒁獾皆贒ocmd.runsql的語句操作的幫助中,有一個選項是UseTransaction。這個選項的是用來確認是否對該語句進行事務性的操作。假如選擇True(默認為True),那么所有的操作都將被當作是一個單獨的原子操作來對數據庫進行操作;假如選擇是False,那么操作將不會被當作事務(在多用戶的情況下可能會出現Dirty Read)的情況。但是這些事務都是在內部完成的,我們無法顯示的通過申明commit或者rollback來控制其操作。
根據我的經驗,ACCESS也無法通過Docmd.OPENQUERY來完成類似的事務顯示操作。假如大家希望實現事務的操作,唯一的用法就是通過WorkSpaceObject.BeginTrans來實現。在Access VBA的幫助文件中,大家可以找到如下的示例:
'BeginBeginTransVB
'To integrate this code
'replace the data source and initial catalog values
'in the connection string
Public Sub Main()
On Error GoTo ErrorHandler
'recordset and connection variables
Dim Cnxn As ADODB.Connection
Dim strCnxn As String
Dim rstTitles As ADODB.Recordset
Dim strSQLTitles As String
'record variables
Dim strTitle As String
Dim strMessage As String
' Open connection
strCnxn = "PRovider='sqloledb';Data Source='MySQLServer';" & _
"Initial Catalog='Pubs';Integrated Security='SSPI';"
Set Cnxn = New ADODB.Connection
Cnxn.Open strCnxn
' Open recordset dynamic to allow for changes
Set rstTitles = New ADODB.Recordset
strSQLTitles = "Titles"
rstTitles.Open strSQLTitles, Cnxn, adOpenDynamic, adLockPessimistic, adCmdTable
Cnxn.BeginTrans
' Loop through recordset and prompt user
' to change the type for a specified title
rstTitles.MoveFirst
Do Until rstTitles.EOF
If Trim(rstTitles!Type) = "psychology" Then
strTitle = rstTitles!Title
strMessage = "Title: " & strTitle & vbCr & _
"Change type to self help?"
' If yes, change type for the specified title
If MsgBox(strMessage, vbYesNo) = vbYes Then
rstTitles!Type = "self_help"
rstTitles.Update
End If
End If
rstTitles.MoveNext
Loop
' Prompt user to commit all changes made
If MsgBox("Save all changes?", vbYesNo) = vbYes Then
Cnxn.CommitTrans
Else
Cnxn.RollbackTrans
End If
' Print recordset
rstTitles.Requery
rstTitles.MoveFirst
Do While Not rstTitles.EOF
Debug.Print rstTitles!Title & " - " & rstTitles!Type
rstTitles.MoveNext
Loop
' Restore original data as this is a demo
rstTitles.MoveFirst
Do Until rstTitles.EOF
If Trim(rstTitles!
Type) = "self_help" Then
rstTitles!Type = "psychology"
rstTitles.Update
End If
rstTitles.MoveNext
Loop
' clean up
rstTitles.Close
Cnxn.Close
Set rstTitles = Nothing
Set Cnxn = Nothing
Exit Sub
ErrorHandler:
' clean up
If Not rstTitles Is Nothing Then
If rstTitles.State = adStateOpen Then rstTitles.Close
End If
Set rstTitles = Nothing
If Not Cnxn Is Nothing Then
If Cnxn.State = adStateOpen Then Cnxn.Close
End If
Set Cnxn = Nothing
If Err <> 0 Then
MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
'EndBeginTransVB
最后,強烈推薦大家閱讀下列文檔,在文檔有一個章節:Transactions在Access中的用法和定義
Advanced Microsoft Jet SQL for Access 2000
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnacc2k/Html/acadvsql.asp