How to connect VBA to postgreSQL and run a query

I am trying to run a query from a Microsoft excel application and could not connect successfully. I have PostgreSQL 9.3 on my local computer and I run 64-bit windows 7. I have an example dvdrental database, which is a demo database. I just need to connect to the database, run a query and view the output on my worksheet (or in the nearest window, or solve the connection problem). Here is what I still do not work.

Option Explicit
Public objConnection As ADODB.Connection 
Public strConnection As String

Public Sub TestPostgresConnection()
Dim strConnection As String
strConnection = "Driver={PostgreSQL Unicode};Server=localhost;Port=5432;   Database=dvdrental;UID=sa;PWD=wrox;"
Set objConnection = New ADODB.Connection
Set objRecordSet = New ADODB.Recordset
objConnection.Open strConnection
With objRecordSet
    .ActiveConnection = objConnection
    .Open "SELECT * FROM actor"
End With
Do While Not objRecordSet.EOF
    Debug.Print objRecordSet.Fields(0).Value
    objRecordSet.MoveNext
Loop
objRecordSet.Close
objConnection.Close
Set objRecordSet = Nothing
Set objConnection = Nothing
End Sub

Here is a list of my links;

Visual Basic Microsoft Excel 14.0 OLE Microsoft Office 14.0 Microsoft Forms 2.0 Microsoft Access 14.0 Microsoft ADO Ext. 6.0 DOL Microsoft ActiveX Data Objects 2.8 Microsoft Windows 6.0 (SP6)

TestPostgresConnection, "[Miscrosoft] [ODBC Driver Manager] "

postgres , - RDBMS .

- , ? . .

+4
1

- . . . , , .

. DSN , , , , .

: http://www.dashbay.com/2011/03/working-with-postgres-on-windows-via-odbc/

. ODBC : https://www.postgresql.org/ftp/odbc/versions/msi/ , : psqlodbc_09_05_0400-x86.zip

Konstantin % WINDIR%\SysWOW64\odbcad32.exe : PostgresSQL ODBC Windows 7

MS Power Query, : https://www.microsoft.com/en-us/download/details.aspx?id=39379

, .

, - , , .

Sub CcQueryPg(sSql As String, Optional sOdbcName As String = "ConnectionNameHere")


'Declare a Connection object
Dim cnDB As New ADODB.Connection

'Declare a Recordset Object
Dim rsRecords As New ADODB.Recordset

'Open the ODBC Connection using this statement
cnDB.Open sOdbcName
rsRecords.Open sSql, cnDB

'Close everything and set the references to nothing
rsRecords.Close
Set rsRecords = Nothing
cnDB.Close
Set cnDB = Nothing
End Sub

Sub SendQuery()

Call CcQueryPg("COPY  sometablenamehere FROM    '/mnt/somepathhere/somefilename.csv' DELIMITER ',' CSV HEADER;")

End Sub

Linux. .

-1

Source: https://habr.com/ru/post/1527798/


All Articles