通过VBA将Excel连接到PostgreSQL

viv*_*vid 9 postgresql excel odbc vba ado

是否可以像SELECT在Excel中的VBA 一样进行查询,这样我就可以从Excel查询PostgreSQL数据库了?

如果可能,请解释我如何连接到数据库.我在谷歌看,但没有找到结果.

sub*_*ero 7

这里有一些代码可以作为参考.希望能帮助到你.

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
Run Code Online (Sandbox Code Playgroud)


Cra*_*ger 6

在PostgreSQL中创建一个描述所需数据的表或视图.

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

看到:

使用Oracle的更好的书面示例,但原理是相同的 - ODBC/ADO.