我正在尝试使用pypyodbc和pandas连接到postgres数据库。我在Centos 7机器上使用Python 2.7。
import pypyodbc
import pandas as pd
conn = pypyodbc.connect("Driver={PostgreSQL};Server=xxx;Port=xxx;Database=xxx;Uid=xxx;Pwd=xxx;")
cur = conn.cursor()
cur.execute("select * from client_list")
col_names = []
for elt in cur.description:
col_names.append(elt[0])
myDF=pd.DataFrame(cur.fetchall(),columns=col_names)
conn.close()
我的连接字符串指向postgresql数据库,我为其配置了ODBC连接。 我已经配置了odbcinst.ini和odbc.ini:
/etc/odbc.ini -
[AlgoDB]
Description = PostgreSQL connection to 'AlgoDB' database
Driver = /usr/lib64/psqlodbc.so
Database = xxx
Servername = xxx
UserName = xxx
Password = xxx
Port = 5432
Protocol = 8.1
ReadOnly = No
RowVersioning = No
ShowSystemTables = No
ShowOidColumn = No
FakeOidIndex = No
/etc/odbcinst.ini:
[PostgreSQL]
Description = ODBC for PostgreSQL
Driver = /usr/lib/psqlodbcw.so
Setup = /usr/lib/libodbcpsqlS.so
Driver64 = /usr/lib64/psqlodbc.so
Setup64 = /usr/lib64/libodbcpsqlS.so
FileUsage = 1
我能够检索查询的结果,但是,字段名称以中文返回:
for index, row in myDF.iterrows():
print(row)
导致:
汣敩瑮湟浡e my client's name
灡彰牵l浡e https://my client's url/
当我使用Windows机器时,我得到的英文属性名称为
client_name my client's name
client_url https://my client's url/
如果我使用isql并在那里运行查询,则字段名称为英文:
sudo isql -v AlgoDB xxx xxx
我做错了什么? 谢谢。
答案 0 :(得分:1)
尝试重新安装ODBC驱动程序并切换到sqlalchemy后,我放弃了pypyodbc:
import sqlalchemy as sa
import pandas as pd
eng = sa.create_engine("postgresql://user:pass@ip:5432/DBName")
myDF = pd.read_sql("select * from client_list",eng)