VBA+SQL访问数据库基本框架
系统框架
代码框架
Public Const ConStrSCM
= "Provider=xxx;Server=xxx;Database=xxx;User ID=xxx;Password=xxx;"
Sub Query_Click
()
Call QueryData
End Sub
Sub QueryData
()
Dim cn
As Object
Dim rs
As Object
Dim i
As Integer
Dim j
As Integer
Dim iID
As Integer
Dim sfirstName
As String
On Error GoTo err_label
Application.ScreenUpdating
= False
Application.DisplayAlerts
= False
Set cn
= CreateObject
("ADODB.Connection")
cn.CommandTimeout
= 300
cn.
Open ConStrSCM
Set rs
= CreateObject
("ADODB.RecordSet")
iID
= Cells
(1, 2).Value
sfirstName
= Cells
(2, 2).Value
sSQL
= "select * from xxx"
Set rs
= cn.Execute
(sSQL
)
If Not rs.EOF
Then
Cells
(6, 1).CopyFromRecordset rs
End If
Call ReleaseDB
(cn
, rs
)
Application.Calculation
= iDefaultCalculate
Exit Sub
err_label
:
Call ReleaseDB
(cn
, rs
)
Application.DisplayAlerts
= True
Application.ScreenUpdating
= True
Application.Calculation
= iDefaultCalculate
MsgBox Err.Description
, vbOKOnly
+ vbExclamation
, "提示"
End Sub
Sub ReleaseDB
(ByRef cn
As Object, ByRef rs
As Object)
If rs.State
= 1 Then
rs.
Close
End If
If cn.State
= 1 Then
cn.
Close
End If
Set rs
= Nothing
Set cn
= Nothing
End Sub