将 pyodbc 连接到 Postgres

Connect pyodbc to Postgres

正在尝试使用 pyodbc 连接到 Postgres。

我可以用 isql 连接到数据库:

echo "select 1" | isql -v my-connector

Returns:

+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL> select 1
+------------+
| ?column?   |
+------------+
| 1          |
+------------+
SQLRowCount returns 1
1 rows fetched

但是当我尝试连接 pyodbc 时:

import pyodbc
con = pyodbc.connect("DRIVER={PostgreSQL Unicode}; DATABASE=<dbname>;     UID=<username>; PWD=<password>; SERVER=localhost; PORT=5432;")

我收到以下错误:

pyodbc.Error: ('08001', '[08001] [unixODBC]connction string lacks some options (202) (SQLDriverConnect)')

obdc.ini 文件如下所示:

[my-connector]
Description         = PostgreSQL connection to '<dbname>' database
Driver              = PostgreSQL Unicode
Database            = <dbname>
Servername          = localhost
UserName            = <username>
Password            = <password>
Port                = 5432
Protocol            = 9.3
ReadOnly            = No
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No
ConnSettings        =

odbcinst.ini 文件如下所示:

[PostgreSQL ANSI]
Description     = PostgreSQL ODBC driver (ANSI version)
Driver          = psqlodbca.so
Setup           = libodbcpsqlS.so
Debug           = 0
CommLog         = 1
UsageCount      = 1

[PostgreSQL Unicode]
Description     = PostgreSQL ODBC driver (Unicode version)
Driver          = psqlodbcw.so
Setup           = libodbcpsqlS.so
Debug           = 0
CommLog         = 1
UsageCount      = 1

备注:

我过去曾使用 psycopg2 连接到 Postgres,但我现在的公司使用 Netezza、Postgres 和 MySQL。我想编写 1 个连接模块,并使用不同的驱动程序连接到不同的数据库。 任何帮助将不胜感激。

-- 谢谢

因为您已经在 odbc.ini 中定义了一个有效的 DSN,您可以直接使用它:

con = pyodbc.connect("DSN=my-connector")

另外,郑重声明,您的连接字符串中的额外空格可能会混淆问题,因为这对我来说效果很好,至少在 Python 2.7

import pyodbc
conn_str = (
    "DRIVER={PostgreSQL Unicode};"
    "DATABASE=postgres;"
    "UID=postgres;"
    "PWD=whatever;"
    "SERVER=localhost;"
    "PORT=5432;"
    )
conn = pyodbc.connect(conn_str)
crsr = conn.execute("SELECT 123 AS n")
row = crsr.fetchone()
print(row)
crsr.close()
conn.close()