python - 在 python 中使用 sqlalchemy.select() 从 Postgresq 数据库中获取数据
问题描述
我正在使用 python 和 SQLalchemy 从表中获取数据。
import sqlalchemy as db
import pandas as pd
DATABASE_URI = 'postgres+psycopg2://postgres:postgresql@localhost:5432/postgres'
engine = db.create_engine(DATABASE_URI)
connection = engine.connect()
project_table = db.Table('project', metadata, autoload=True, autoload_with=engine)
在这里,我想根据我拥有的 id 列表获取记录。
l=[557997, 558088, 623106, 558020, 623108, 557836, 557733, 622792, 623511, 623185]
query1 = db.select([project_table ]).where(project_table .columns.project_id.in_(l))
#sql query= "select * from project where project_id in l"
Result = connection.execute(query1)
Rset = Result.fetchall()
df = pd.DataFrame(Rset)
print(df.head())
在这里,当我打印 df.head() 时,我得到一个空数据框。我无法将列表传递给上述查询。有没有办法将列表发送到上述查询。
结果应包含表中等于给定 project_id 的行。IE
project_id project_name project_date project_developer
557997 Test1 24-05-2011 Ajay
558088 Test2 24-06-2003 Alex
这些行将被插入到数据集中。查询是
"select * from project where project_id in (557997, 558088, 623106, 558020, 623108, 557836, 557733, 622792, 623511, 623185)"
在这里,因为我不能给出静态值,所以我会将值插入到一个列表中,并将这个列表作为参数传递给查询。这是我遇到问题的地方。我不能将列表作为参数传递给 db.select()。如何将列表传递给 db.select()
解决方案
经过多次跟踪后,我发现由于查询正在获取大量数据并且我的工作站中的内存也较少,因此查询返回 null(无结果)。所以我所做的是
Result = connection.execute(query1)
while True:
rows = Result.fetchmany(10000)
if not rows:
break
for row in rows:
table_data.append(row)
pass
df1 = pd.DataFrame(table_data)
df1.columns = columns
在此之后,程序运行良好。
推荐阅读
- html - 在不调整 div 大小的情况下调整图像大小
- c# - 在 DataTable 中求和相等的数据并将它们传递给新的 DataTable C#
- sql-server - 在 SSIS 中,如何将 unicode 数据类型转换为 excel 列?
- react-native - 在 onRegionChange 之后映射回之前的位置
- xamarin - Xamarin Forms 中相同大小的标签
- python - 在 Django 中的数据库中查找电话号码后添加其他字段
- c - 设置超出程序中断的内存不会出现段错误
- c# - 射弹不会杀死玩家船?
- android - 从导入的库访问项目中的 jar - gradle / android studio
- android - 如何在我的 Android 应用程序中从 Mi Band 3 获取连续的心率数据