首页 > 解决方案 > 在 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()

标签: pythonpostgresqlsqlalchemy

解决方案


经过多次跟踪后,我发现由于查询正在获取大量数据并且我的工作站中的内存也较少,因此查询返回 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

在此之后,程序运行良好。


推荐阅读