简体   繁体   中英

Attempting to connect VBA to PostgreSQL (not excel)

I'm fairly new to PostgreSQL, and I'm trying to connect to a table via VBA from Autodesk Inventor - not MSEXCEL.

I'm using the code below, but I get the error shown below when I try to connect. If I try the same code in Excel, it works fine - it only errors in Autodesk Inventor.

I've checked my project references, and they match. I'm not sure what else to try. Searching on that error brings up some permissions-related issues, but they seem to be linked to Excel. Are the methods I'm using here somehow exclusive to Excel?

在此处输入图像描述

Sub PostGresTest()

Dim oConn As New ADODB.Connection
Dim cmd As New ADODB.Command
' Connection Parameters
Dim strUsername As String
Dim strPassword As String
Dim strServerAddress As String
Dim strDatabase As String
' User:
strUsername = "TEST"
' Password:
strPassword = "password"
' Server Address:
strServerAddress = "localhost"
' Database
strDatabase = "postgres"

oConn.Open "DSN=PostgreSQL35W;" & _
"Database=" & strDatabase & ";" & _
"Uid=" & strUsername & ";" & _
"Pwd=" & strPassword
.......

I've omitted the rest of the code since the error occurrs on the oConn.Open line.

Any suggestions?

I made a few changes to the code and my DSN settings then my PC rebooted overnight for a windows update. This morning, everything worked. I suggest it was probably the reboot that did it because it didn't work before rebooting, but maybe my settings were wrong anyway.

I found a Stack question that suggested that the DSN should be set up under 'System DSN' not 'User DSN' - (sorry - I lost the link) -So I made that change too.

Here's the final code:

Function PostGresTest(Optional StrSQL As String = "")

Dim oConn As New ADODB.Connection
Dim cmd As New ADODB.Command
' Connection Parameters
Dim strUsername As String
Dim strPassword As String
Dim strServerAddress As String
Dim strDatabase As String
' User:
strUsername = "TEST"
' Password:
strPassword = "password"
' Server Address:
strServerAddress = "localhost"
' Database
strDatabase = "postgres"
   
Set oConn = CreateObject("ADODB.Connection")
oConn.Open "Driver={PostgreSQL UNICODE};" & _
         "DSN=PostgreSQL35W;" & _
         "Database=" & strDatabase & ";" & _
         "SERVER=" & strServerAddress & ";" & _
         "Uid=" & strUsername & ";" & _
         "Pwd=" & strPassword
 .....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM