2015-12-22 105 views
7

嘗試使用pyodbc連接到Postgres。將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個連接模塊,並使用不同的驅動程序連接到不同的數據庫。 任何幫助將不勝感激。

- 感謝

+0

一開始,你可以嘗試,包括所有的A來自連接字符串中的odbc.ini條目的參數,並查看是否有效。 –

+0

@GordThompson - 謝謝。試過了,仍然沒有運氣。 –

+1

如果你只是使用'DSN = my-connector',它會工作嗎? –

回答

4

既然你已經有一個工作DSN定義在ODBC.INI你可以使用:

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()