Visual Basic 6.0 / VBA (Access/Excel) 透過 ADO 連接 SQL Server,常見連接字串模式與錯誤處理範本。
| 模式 | 連接字串範例 | 適用場景 |
|---|---|---|
| SQL Server 驗證 (sa/密碼) | Provider=SQLOLEDB.1;Data Source=ServerIP;Initial Catalog=DBName;User ID=sa;Password=Pwd; | 舊系統、需指定帳號 |
| Windows 整合驗證 (當前使用者) | Provider=SQLOLEDB.1;Data Source=ServerIP;Initial Catalog=DBName;Integrated Security=SSPI; | 內部網域環境、最安全 |
| 本地實例 (.) | Provider=SQLOLEDB.1;Data Source=.;Initial Catalog=DBName;Integrated Security=SSPI; | 開發機、單機部署 |
| 具名實例 | Provider=SQLOLEDB.1;Data Source=ServerIP\InstanceName;Initial Catalog=DBName;Integrated Security=SSPI; | 多實例伺服器 |
' 標準模組 modDB.bas
Option Explicit
Public gConn As ADODB.Connection
Public Const gConnStr As String = "Provider=SQLOLEDB.1;Data Source=192.168.1.50;Initial Catalog=HumanDB;Integrated Security=SSPI;"
Public Sub DB_Connect()
On Error GoTo ErrHandler
If gConn Is Nothing Then Set gConn = New ADODB.Connection
If gConn.State = adStateOpen Then Exit Sub
gConn.ConnectionString = gConnStr
gConn.CommandTimeout = 30
gConn.ConnectionTimeout = 15
gConn.CursorLocation = adUseClient ' 客戶端游標,支援離線 Recordset
gConn.Open
Exit Sub
ErrHandler:
Select Case Err.Number
Case -2147467259, -2147217900 ' SQL Server 不存在/未啟動
MsgBox "資料庫伺服器未啟動或無法連線,請檢查網路與 SQL Server 服務。", vbCritical, "連線失敗"
Case -2147217843 ' 登入失敗
MsgBox "資料庫登入失敗,請確認帳號密碼或 Windows 權限。", vbCritical, "登入失敗"
Case Else
MsgBox "資料庫連線錯誤: " & Err.Number & " - " & Err.Description, vbCritical, "錯誤"
End Select
Set gConn = Nothing
End Sub
Public Sub DB_Disconnect()
On Error Resume Next
If Not gConn Is Nothing Then
If gConn.State = adStateOpen Then gConn.Close
Set gConn = Nothing
End If
End Sub
' 範例:執行無回傳 SQL (INSERT/UPDATE/DELETE)
Public Function ExecSQL(ByVal sql As String, ParamArray params() As Variant) As Long
On Error GoTo ErrExec
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = gConn
.CommandText = sql
.CommandType = adCmdText
.CommandTimeout = 60
' 參數綁定 (簡易示範,實際建議用 CreateParameter)
Dim i As Long
For i = LBound(params) To UBound(params) Step 2
.Parameters.Append .CreateParameter(CStr(params(i)), adVariant, adParamInput, , params(i + 1))
Next
End With
ExecSQL = cmd.Execute(RecordsAffected:=ExecSQL)
Exit Function
ErrExec:
MsgBox "SQL 執行錯誤: " & Err.Description & vbCrLf & sql, vbCritical
ExecSQL = -1
End Function
' 範例:查詢回傳 Recordset
Public Function QueryRS(ByVal sql As String, ParamArray params() As Variant) As ADODB.Recordset
On Error GoTo ErrQuery
Dim cmd As ADODB.Command, rs As ADODB.Recordset
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = gConn
.CommandText = sql
.CommandType = adCmdText
Dim i As Long
For i = LBound(params) To UBound(params) Step 2
.Parameters.Append .CreateParameter(CStr(params(i)), adVariant, adParamInput, , params(i + 1))
Next
End With
Set rs = New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockReadOnly
rs.Open cmd
Set QueryRS = rs
Exit Function
ErrQuery:
MsgBox "查詢錯誤: " & Err.Description, vbCritical
Set QueryRS = Nothing
End Function
Private Sub Form_Load()
Call DB_Connect
Dim rs As ADODB.Recordset
Set rs = QueryRS("SELECT EmpID, EmpName FROM Employees WHERE DeptID = ?", "@DeptID", 10)
Do While Not rs.EOF
lstEmployees.AddItem rs("EmpName")
rs.MoveNext
Loop
rs.Close
End Sub
Private Sub Form_Unload(Cancel As Integer)
Call DB_Disconnect
End Sub
Command.Parameters 防 SQL Injection、自動處理型別/日期格式。Connection,利用連接池。adUseClient 適合離線操作、排序/篩選;adUseServer 適合大量資料流式讀取。Recordset.Close、Set rs = Nothing、Connection.Close。;Codepage=65001,資料表欄位用 NVARCHAR,VB6 專案設定 Unicode 支援。VB6/VBA 雖屬經典技術,但大量內部系統仍在運作。規範連接管理與參數化查詢,能延長系統壽命並大幅降低安全風險。