您只需要打開一次連接。這實際上意味着您可以在該活動連接上執行多個查詢。您必須關閉連接並釋放參考(專門用ADODB)以避免碰到碰撞和其他連接相關問題。
如果您知道要執行的查詢,可以創建一個數組(或集合),並向隊列中添加查詢。
雖然你已經有了一個開放的連接與你一起工作,你可以繼續執行查詢。
通過代碼掃描,你和我之間沒有太大的區別,所以你應該能夠看到發生了什麼和在哪裏。請,請在評論的問題,如果有不清楚的地方現在
Sub DbConnection()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="
cn.Open strConn
Dim queryArr, i
queryArr = Array("SELECT * FROM [MyTable]", "SELECT * FROM [MyOtherTable]")
For i = LBound(queryArr) To UBound(queryArr)
ExecuteQuery queryArr(i), cn, rs
Next i
cn.Close
Set cn = Nothing
End Sub
Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open CStr(query)
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
End Sub
,你只需要執行DBConnection()
一次,你在陣列中列出的所有查詢將被執行。
或者,如果您的查詢是在運行時創建的,則可以將它作爲參數傳遞給DbConnection()
。
Sub DbConnection(queryQueue As Collection)
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=HELIUM\PRI; Database=sourcedata; UID=tabula; PWD=Tabula123!"
cn.Open strConn
For i = 1 To queryQueue.Count
ExecuteQuery queryQueue.Item(i), cn, rs
Next i
cn.Close
Set cn = Nothing
End Sub
Private Sub ExecuteQuery(query As Variant, ByRef cn As ADODB.Connection, ByRef rs As ADODB.Recordset)
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open CStr(query)
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
End Sub
更新:
你可以聲明爲全局變量的連接。現在,您可以隨意多次運行DBConnection()
,並且每次都不會創建新連接。相反,您將使用全局連接對象。
Option Explicit
Public cn As ADODB.Connection
Sub DbConnection()
Set cn = New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strConn As String
strConn = "Driver={SQL Server};Server=; Database=; UID=; PWD="
cn.Open strConn
Set rs = New ADODB.Recordset
With rs
.ActiveConnection = cn
.Open "SELECT * FROM [MyTable]"
Sheets(1).Range("A1").CopyFromRecordset rs
.Close
End With
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
沒有看到更多的宏代碼很難回答,但它似乎永遠不會關閉連接,所以,每次運行宏時都會創建一個新的連接。 – Tony
@Tony,我寫了conn.Close結尾,但它仍然創建新的連接(rec1.Close崩潰宏)。還有什麼我需要關閉? – frickskit