按照这篇文章中的代码,我正在尝试使用 VBA 调用 WinAPI 函数SQlConfigDataSource()
来创建新的 ODBC 源。这是我的代码:
Const ODBC_ADD_SYS_DSN = 4 'Add a system data source
Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal _
hwndParent As Long, ByVal fRequest As Long, ByVal _
lpszDriver As String, ByVal lpszAttributes As String) As Long
Private Declare Function SQLInstallerError Lib "ODBCCP32.DLL" (ByVal iError As Integer, _
pfErrorCode As Long, ByVal lpszErrorMessage As String, ByVal cbErrorMsgMax As Integer, _
pcbErrorMsg As Integer) As Integer
Private Const SQL_SUCCESS = 0
Private Const SQL_SUCCESS_WITH_INFO = 1
Private Const SQL_NO_DATA = 100
Private Const SQL_ERROR = (-1)
Private Const SQL_MAX_MESSAGE_LENGTH = 512
Function Build_SystemDSN(dataSourceName As String, server_instance As String, database As String)
'SQLConfigDataSource parameters
Dim Driver As String
Dim Ret As Long
Dim Attributes As String
'SQLInstallerError parameters
Dim iret As Integer
Dim lpszErrMess As String
Dim iErr As Integer 'may be 1 - 8
Dim pfErrCode As Long
lpszErrMess = Space(SQL_MAX_MESSAGE_LENGTH)
Driver = "SQL Server"
'attributes are the connection information
Attributes = "server=" & server_instance & Chr(0)
Attributes = Attributes & "DSN=" & dataSourceName & Chr(0)
Attributes = Attributes & "Database=" & database & Chr(0)
'use this line if you want to use the users name and password
Attributes = Attributes & "Trusted_Connection=Yes" & Chr(0)
Ret = SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, Driver, Attributes)
'ret is equal to 1 on success and 0 if there is an error
If Ret <> 1 Then
iErr=1
iret = SQLInstallerError(iErr, pfErrCode, lpszErrMess, SQL_MAX_MESSAGE_LENGTH, 0)
MsgBox "DSN Creation Failed: " & pfErrCode
End If
End Function
我将函数称为:
Sub testBuildDSN()
Dim oc As New ODBCCreator
oc.Build_SystemDSN "XYSource", "SQLRM101\sqlrm101a", "XYoppid_abc_prod"
End Sub
但是SQLConfigDataSource()
返回 0。我认为这是因为我的服务器/实例对中有一个反斜杠;根据MSDN,这不是属性集中允许的字符。如何使用此功能设置服务器和实例?
编辑:我添加了代码来输出SQLInstallerError()
数据。当我查看错误 1(我猜这是我刚刚拨打的电话中的错误?)然后我得到一个pfErrorCode
值“19”。我不知道这是什么意思。