简体   繁体   English

通过VBA将Excel连接到PostgreSQL

[英]Connecting Excel to PostgreSQL via VBA

Is it possible to make query like SELECT from VBA in Excel, so I can query a PostgreSQL DB from Excel? 是否可以在Excel中从VBA进行SELECT查询,这样我就可以从Excel查询PostgreSQL数据库了?

If is possible please explain me how to connect to the database. 如果可能,请解释我如何连接到数据库。 I was looking in Google but found no results. 我在谷歌看,但没有找到结果。

Here's some code can use as reference. 这里有一些代码可以作为参考。 Hope it helps. 希望能帮助到你。

Sub SelectBasic()

        Dim objDb_con
        Dim strSomeValue As String

        Set objDb_con = CreateObject("ADODB.Connection")
        Set Rsdatatype = CreateObject("ADODB.RecordSet")

        glbConnString = Trim(ActiveSheet.Range("B1").Value)
        //Connection string format:Driver={PostgreSQL Unicode};Database=MyDB;server=192.16*.*.**;UID=USERID;Pwd=pasword //comment it
        If glbConnString = "" Then
         MsgBox "Enter the Connection String"
        Else:

        objDb_con.Open glbConnString

        strSql = "select strSomeValue  from SOMETABLE where Something=1"
        Rsdatatype.Open strSql, objDb_con, adOpenKeyset, adLockpessimistic
        If Rsdatatype.EOF = False Then strSomeValue = Rsdatatype.Fields(0).Value
        Rsdatatype.Close

        End If
        objDb_con.Close
    End Sub

Create a table or view in PostgreSQL that describes the data you want. 在PostgreSQL中创建一个描述所需数据的表或视图。

Use an ODBC or ADO connection from VBA to connect to PostgreSQL. 使用VBA中的ODBC或ADO连接来连接到PostgreSQL。 If using ODBC you'll need to create a DSN via odbcad32.exe then use the DSN in VB, it isn't easy to just connect directly. 如果使用ODBC,则需要通过odbcad32.exe创建DSN,然后在VB中使用DSN,直接连接并不容易。

See: 看到:

Better written eample that uses Oracle , but the principles are the same - ODBC/ADO. 使用Oracle的更好的书面示例 ,但原理是相同的 - ODBC / ADO。

Even for 64-bit Windows, Excel VBA needs the 32-bit ODBC driver . 即使对于64位Windows,Excel VBA也需要32位ODBC驱动程序

Create a DSN via %windir%\\SysWOW64\\odbcad32.exe . 通过%windir%\\SysWOW64\\odbcad32.exe创建DSN。 Indeed, typing odbcad32.exe points towards the 64-bit version where you can't find the proper 32-bit drivers by default. 实际上,键入odbcad32.exe指向64位版本,默认情况下您找不到正确的32位驱动程序。

Source: https://github.com/windweller/postgresql-excel-addIn 资料来源: https//github.com/windweller/postgresql-excel-addIn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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