将pyodbc连接到Postgres

时间:2015-12-22 02:21:51

标签: postgresql python-3.x ubuntu-14.04 pyodbc

尝试使用pyodbc连接到Postgres。

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

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

返回:

+---------------------------------------+
| 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

注意:

  • Ubuntu 14.04
  • Python 3
  • Postgresql 9.3

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

- 谢谢

1 个答案:

答案 0 :(得分:8)

由于您已经在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()