Python 使用sqlalchemy从PostgreSQL查询返回数据帧
我想查询PostgreSQL数据库,并将输出作为数据帧返回 我使用“SqlAlchemy”创建了与数据库的连接:Python 使用sqlalchemy从PostgreSQL查询返回数据帧,python,postgresql,pandas,sqlalchemy,Python,Postgresql,Pandas,Sqlalchemy,我想查询PostgreSQL数据库,并将输出作为数据帧返回 我使用“SqlAlchemy”创建了与数据库的连接: from sqlalchemy import create_engine engine = create_engine('postgresql://user@localhost:5432/mydb') 我将数据帧写入数据库表: i=pd.read_csv(path) i.to_sql('Stat_Table',engine,if_exists='replace') 基于,看起来p
from sqlalchemy import create_engine
engine = create_engine('postgresql://user@localhost:5432/mydb')
我将数据帧写入数据库表:
i=pd.read_csv(path)
i.to_sql('Stat_Table',engine,if_exists='replace')
基于,看起来pd.read\u sql\u query()应该接受SQLAlchemy引擎:
a=pd.read_sql_query('select * from Stat_Table',con=engine)
但它抛出了一个错误:
ProgrammingError: (ProgrammingError) relation "stat_table" does not exist
我使用的是熊猫版本0.14.1
正确的方法是什么?错误消息告诉您名为:
stat_table
不存在(关系是postgres中的表)。因此,当然不能从中选择行。执行以下操作后检查数据库:
i.to_sql('Stat_Table',engine,if_exists='replace')
并查看是否在数据库中创建了一个同名的表
当我使用您的read语句时:
df = pd.read_sql_query('select * from Stat_Table',con=engine)
我从postgres数据库中获取数据,因此它没有问题。您被PostgreSQL的案例敏感性问题所困扰。如果在查询中引用表名,它将起作用:
df = pd.read_sql_query('select * from "Stat_Table"',con=engine)
但就我个人而言,我建议在将表写入数据库时始终使用小写的表名(和列名),以防止出现此类问题
从PostgreSQL文档(): 引用标识符也使其区分大小写,而未引用的名称总是折叠成小写 再解释一下:您已将一个名为
Stat\u table
的表写入数据库(sqlalchemy将引用此名称,因此它将在postgres数据库中写入为“Stat\u table”)。在执行查询时,'select*from Stat\u Table'
未加引号的表名将转换为小写的Stat\u Table
,因此您会收到未找到此表的消息
另请参见下面给出的阅读postgres sql数据和图片链接
import psycopg2 as pg
import pandas.io.sql as psql
connection = pg.connect("host=localhost dbname=kinder user=your_username password=your_password")
dataframe = psql.read_sql('SELECT * FROM product_product', connection)
product_category = psql.read_sql_query('select * from product_category', connection)
这里的聚会迟到了,但给你一个完整的例子:
import pandas as pd
import psycopg2 as pg
engine = pg.connect("dbname='my_db_name' user='pguser' host='127.0.0.1' port='15432' password='pgpassword'")
df = pd.read_sql('select * from Stat_Table', con=engine)
您需要运行以下程序来安装ubuntu的依赖项:
pip-optg2二进制SQLAlchemy
关于这个主题的熊猫文档谢谢。选中,表确实已创建。正如@joris所说,表名中存在区分大小写的问题:我重新编写了表:
I.to_sql('stat_table',engine,if_exists='replace')
,然后它就工作了:a=pd.read_sql_query('select*from stat_table',engine)
@Imart999,当我写到:查看是否在数据库中创建了一个同名的表——该名称引用了错误消息中的名称,即stat\u table
。错误消息名称与您得到的任何错误都相关。由于python从不出错,因此该错误意味着您的代码从未创建名为stat\u name
的表。看看我是如何把表名stat\u name
放在它自己的段落中并突出显示出来的——这应该会让你注意到它。对了,我明白了。我同时看到了这两种反应(离线时)。我看到您的回答使我得到了@jor明确说明的相同答案(例如,确保编写了名为stat\u table
的表)。感谢您的回复。@Imart999,无需担心。当我重读我的答案时,我意识到那个名字所指的并不完全清楚。我应该把你的代码删掉。