尝试使用pyodbc连接到Postgres.
我可以用isql连接到DB:
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=; UID= ; PWD= ; SERVER=localhost; PORT=5432;")
我收到以下错误:
pyodbc.Error: ('08001', '[08001] [unixODBC]connction string lacks some options (202) (SQLDriverConnect)')
obdc.ini文件如下所示:
[my-connector] Description = PostgreSQL connection to '' database Driver = PostgreSQL Unicode Database = Servername = localhost UserName = 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个连接模块,并使用不同的驱动程序连接到不同的数据库.任何帮助将不胜感激.
- 谢谢
由于您已经在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()