我正在尝试将临时表与SQLAlchemy一起使用,并将其与现有表相连接。这就是我目前所拥有的
engine = db.get_engine(db.app, 'MY_DATABASE')
df = pd.DataFrame({"id": [1, 2, 3], "value": [100, 200, 300], "date": [date.today(), date.today(), date.today()]})
temp_table = db.Table('#temp_table',
db.Column('id', db.Integer),
db.Column('value', db.Integer),
db.Column('date', db.DateTime))
temp_table.create(engine)
df.to_sql(name='tempdb.dbo.#temp_table',
con=engine,
if_exists='append',
index=False)
query = db.session.query(ExistingTable.id).join(temp_table, temp_table.c.id == ExistingTable.id)
out_df = pd.read_sql(query.statement, engine)
temp_table.drop(engine)
return out_df.to_dict('records')
这不会返回任何结果,因为to_sql
没有运行的insert语句(我认为这是因为它们是使用sp_prepexec
运行的,但我不完全确定)。
然后我试着写出SQL语句(CREATE TABLE #temp_table...
,INSERT INTO #temp_table...
,SELECT [id] FROM...
),然后运行pd.read_sql(query, engine)
。我收到错误信息
This result object does not return rows. It has been closed automatically.
我想这是因为语句不仅仅是SELECT
?
我如何解决这个问题(两种解决方案都可以,尽管第一种方案更可取,因为它避免了硬编码的SQL)。为了清楚起见,我不能修改现有数据库中的模式这是一个供应商数据库。
如果要插入到临时表中的记录数很小/中等,一种可能是使用
literal subquery
或values CTE
而不是创建临时表。假设还要将以下数据插入到
temp
表中:创建包含该数据的CTE或子查询:
使用所需的联接和筛选器创建最终查询:
最后,获取pandas数据帧:
您可以尝试使用另一个解决方案-进程键控表
。。。
http://www.sommarskog.se/share_data.html#prockeyed
相关问题 更多 >
编程相关推荐