如何使用[server] \ [instance]属性调用SqlConfigDataSource()?

时间:2013-10-15 21:43:48

标签: vba winapi odbc

遵循this post中的代码,我正在尝试使用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”。我不知道这意味着什么。

1 个答案:

答案 0 :(得分:1)

如果SQLConfigDataSource失败,您需要致电SQLInstallerError以找出原因。

SQLInstallerError返回错误代码19. ODBC错误代码位于odbcinst.h,19位为ODBC_ERROR_WRITING_SYSINFO_FAILED

这很可能是因为您没有必要的权限来创建系统范围的数据源名称。

尝试以管理员身份运行代码。