如何自动创建带用户名密码的SQL Server ODBC DSN?
如何自动创建带指定用户名和密码的SQL Server ODBC DSN?
你当前的VB代码可成功创建Windows身份验证的SQL Server ODBC DSN,但将Trusted_Connection=true替换为UID=username1;PWD=password1启用SQL身份验证时,DSN创建失败。问题出在属性格式错误——SQLConfigDataSource要求每个配置项必须是独立的、以Chr$(0)分隔的条目,不能用分号将UID和PWD合并在同一行。
修正后的关键代码行
将错误的合并行:
strAttributes = strAttributes & "UID=username1;PWD=password1" & Chr$(0)
替换为两个独立的属性条目:
strAttributes = strAttributes & "UID=username1" & Chr$(0) strAttributes = strAttributes & "PWD=password1" & Chr$(0)
完整修正后的Command1_Click代码
'//Add DSN Private Sub Command1_Click() #If Win32 Then Dim intRet As Long #Else Dim intRet As Integer #End If Dim strDriver As String Dim strAttributes As String strDriver = "SQL Server" strAttributes = "SERVER=MSSQLSERVER1" & Chr$(0) strAttributes = strAttributes & "DESCRIPTION=Temp DSN" & Chr$(0) strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0) strAttributes = strAttributes & "DATABASE=MonoDB" & Chr$(0) ' 替换为独立的UID和PWD属性 strAttributes = strAttributes & "UID=username1" & Chr$(0) strAttributes = strAttributes & "PWD=password1" & Chr$(0) 'To show dialog, use Form1.Hwnd instead of vbAPINull. intRet = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, _ strDriver, strAttributes) If intRet Then MsgBox "DSN Created" Call TestDSNConnection("DSN_TEMP") Else MsgBox "Create Failed" End If End Sub
关键说明
SQLConfigDataSource的lpszAttributes参数是空字符分隔的属性列表,每个属性必须是键=值格式,单独作为一个条目,用Chr$(0)分隔。- 不能像普通ODBC连接字符串那样用分号
;合并多个属性,这是导致创建失败的核心原因。
内容的提问来源于stack exchange,提问作者Junk Man
相关产品推荐
相关产品推荐

