通过 VBA 将 Excel 连接到 PostgreSQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13230456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:22:33  来源:igfitidea点击:

Connecting Excel to PostgreSQL via VBA

excelpostgresqlvbaodbcado

提问by vivid

Is it possible to make query like SELECTfrom VBA in Excel, so I can query a PostgreSQL DB from Excel?

是否可以像SELECT从 Excel 中的 VBA进行查询,以便我可以从 Excel 查询 PostgreSQL DB?

If is possible please explain me how to connect to the database. I was looking in Google but found no results.

如果可能,请向我解释如何连接到数据库。我在谷歌搜索,但没有找到任何结果。

采纳答案by Craig Ringer

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. If using ODBC you'll need to create a DSN via odbcad32.exethen use the DSN in VB, it isn't easy to just connect directly.

使用来自 VBA 的 ODBC 或 ADO 连接连接到 PostgreSQL。如果使用 ODBC,您需要通过创建 DSNodbcad32.exe然后在 VB 中使用 DSN,直接连接并不容易。

See:

看:

Better written eample that uses Oracle, but the principles are the same - ODBC/ADO.

使用 Oracle 编写的更好的示例,但原理是相同的 - ODBC/ADO。

回答by subZero

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

回答by Candide

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. Indeed, typing odbcad32.exepoints towards the 64-bit version where you can't find the proper 32-bit drivers by default.

通过%windir%\SysWOW64\odbcad32.exe. 实际上,键入odbcad32.exe指向 64 位版本,默认情况下您找不到合适的 32 位驱动程序。

Source: https://github.com/windweller/postgresql-excel-addIn

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