Mysql

到同一張表的並發連接

  • July 2, 2018

我們是一家小公司,大約有 10 人使用數據庫伺服器。

我有這個連接到數據庫並在表中填充大約 40 行數據的應用程序。然後呼叫儲存過程來處理數據,然後再將數據插入另一個表,然後截斷該表。

如果兩個人同時執行應用程序,是否有可能,數據可能是無意義的。如果是這樣,我該如何防止這種情況?

我建議使用臨時表而不是插入和截斷。它們對其他會話是不可見的,因此您可以讓多個會話創建相同的“TEMPTABLEA”、插入記錄、刪除記錄,甚至銷毀 TEMP TABLE,而不會干擾其他使用者的工作。當您終止會話時,臨時表會自動被銷毀。

我將放置一段 VBA 程式碼,您必須將其添加到您的程式碼中。(確保您有這些參考 Microsoft ActiveX Data Objects 6.1 Library 和 Microsoft ActiveX Data Objects Recordset 6.1 Library )

這是程式碼:

Public Sub Routine()
   On Error GoTo ErrorHandler
   Dim Cnxn As ADODB.Connection
   Dim strCnxn As String

   Dim sqlStr0 As String
   'Dim ...all SQL strings you need
   'Dim ...all recordsets you need


   'Open Connection and begin transaction
   strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
               "Initial Catalog='[Your Data base here]';Integrated Security='SSPI';"
   Set Cnxn = New ADODB.Connection
   Cnxn.Open strCnxn
   Cnxn.BeginTrans

   'Sql String to create a TEMPORARY TABLE using YOUR ORIGIN TABLE as a TEMPLATE
   sqlStr0 = "create temporary table TempTableA as select * from tableA where 1 = 2;"
   Cnxn.Execute sqlStr0

   'Put your code here to insert the 40 records into TempTableA
   'Put your code here to move records from TempTableA to definitive TableB
   'Do not worry about TempTableA anymore. It will be destroyed.

   Cnxn.CommitTrans
   Cnxn.Close
   Set Cnxn = Nothing

   Exit Sub

ErrorHandler:
   ' clean up
   If Not Cnxn Is Nothing Then
       If Cnxn.State = adStateOpen Then
           Cnxn.RollbackTrans
           Cnxn.Close
       End If
       Set Cnxn = Nothing
   End If
   If Err <> 0 Then
       MsgBox Err.Source & "-->" & Err.Description, , "Error"
   End If
End Sub

祝你好運!!

引用自:https://dba.stackexchange.com/questions/210884