gpt4 book ai didi

python - pandas.read_sql 使用 SQLAlchemy 未提交读取

转载 作者:太空宇宙 更新时间:2023-11-03 15:44:09 25 4
gpt4 key购买 nike

我正在尝试使用 pandas 函数 pd.read_sql 读取已在 SQLAlchemy session 中创建、添加和刷新但未提交的记录。所以我想在 SQLAlchemy session 中创建一个对象,并在调用 commit 之前用 pandas 查询它。使用 pandas 0.22.0 和 SQLAlchemy 1.1.10。

我已经尝试在 create_engine 上设置 isolation_level,以及将隔离级别设置为“READ UNCOMMITTED”的各种其他方法,但这似乎不起作用。下面的最小示例:

# Import packages 

import pandas as pd
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker

# Set up an example ORM

Base = declarative_base()
class Record(Base):
__tablename__ = 'records'
id = Column(Integer, primary_key=True)
foo = Column(String(255))

# Create a session and engine:

database='foobar'
user=''
password = ''
host = 'localhost'
port = '5432'

connection_string = f"postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}"
engine = create_engine(connection_string, encoding = 'utf8', convert_unicode = True,
isolation_level='READ_UNCOMMITTED'
)
session = sessionmaker()
session.configure(bind=engine)
db = session()

# Set up the example record:

Record.__table__.create(bind=engine)
record = Record(foo='bar')
db.add(record)
db.flush()

# Attempt to query:

records = pd.read_sql('select * from records', db.get_bind())
assert records.empty

我正在寻找一种解决方案,它会导致上述代码在最后一行抛出 AssertionErrorrecords.empty 当前评估为 true。

最佳答案

当然,我一发帖就明白了。对于后代:使用 db.connection() 而不是 db.get_bind()

关于python - pandas.read_sql 使用 SQLAlchemy 未提交读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51068215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com