使用VB6进行SQL Server的动态DSN

时间:2013-07-12 02:57:47

标签: dynamic vb6 dsn

我想在VB6应用程序中创建动态DSN。我在我的MODULE中尝试了以下代码。使用以下Microsoft链接 - http://support.microsoft.com/kb/171146

我的代码在这里 -

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

Public Function PrepareDSN(strServerName As String, strDBName As String, strDSN As String, strDBUser As String, strDBUserPassword As String) As Boolean
On Error GoTo error_hdl
Dim boolError As Boolean
Dim strDSNString As String
PrepareDSN = False

strDSNString = Space(MAX_BUFFER_SIZE)
strDSNString = ""
strDSNString = strDSNString & "DSN=" & strDSN & Chr(0)
strDSNString = strDSNString & "DESCRIPTION=" & "DSN Created Dynamically On " & CStr(Now) & Chr(0)
strDSNString = strDSNString & "Server=" & strServerName & Chr(0)
strDSNString = strDSNString & "DATABASE=" & strDBName & Chr(0)
strDSNString = strDSNString & Chr(0)



 If Not CBool(SQLConfigDataSource(0, _
                        ODBC_ADD_DSN, _
                        ODBCDriverDescription, _
                        strDSNString)) Then
    boolError = True
    MsgBox ("Error in PrepareDSN::SQLConfigDataSource")


  End If

If boolError Then
    Exit Function
End If
PrepareDSN = True
Exit Function

error_hdl:
    MsgBox "PrepareDSN_ErrHandler::" & err.Description
End Function

这里我的函数“SQLConfigDataSource”总是返回false。请建议。

1 个答案:

答案 0 :(得分:2)

缺少两件事。

1)您没有定义请求类型ODBC_ADD_DSN 2)未设置数据库驱动程序

以下是修改后的代码,我成功连接到我的数据库。

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 Const ODBC_ADD_DSN = 1 'Define request type
'!!!!!!!!!!
Public Function PrepareDSN(strServerName As String, strDBName As String, strDSN As String, strDBUser As String, strDBUserPassword As String) As Boolean
On Error GoTo error_hdl
Dim boolError As Boolean
Dim strDSNString As String
PrepareDSN = False

strDSNString = Space(MAX_BUFFER_SIZE)
strDSNString = ""
strDSNString = strDSNString & "DSN=" & strDSN & Chr(0)
strDSNString = strDSNString & "DESCRIPTION=" & "DSN Created Dynamically On " & CStr(Now) & Chr(0)
strDSNString = strDSNString & "Server=" & strServerName & Chr(0)
strDSNString = strDSNString & "DATABASE=" & strDBName & Chr(0)
strDSNString = strDSNString & Chr(0)


'!!!!!!!!!!
Const Driver As String = "SQl Server" 'Set driver descr
'!!!!!!!!!!
 If Not CBool(SQLConfigDataSource(0, _
                         ODBC_ADD_DSN, _
                        Driver, _
                        strDSNString)) Then
    boolError = True
    MsgBox ("Error in PrepareDSN::SQLConfigDataSource")


  End If

If boolError Then
    Exit Function
End If
PrepareDSN = True
Exit Function

error_hdl:
    MsgBox "PrepareDSN_ErrHandler::" & Err.Description
End Function