【发布时间】:2019-10-18 14:01:16
【问题描述】:
我正在尝试使用 sqlalchemy 从文件中执行 sql 查询。
当我运行查询时,我得到一个结果,说它影响了 x 行,但是当我检查数据库时,它实际上并没有向表中插入任何内容。
这是我当前的代码:
def import_to_db(df, table_name):
df.to_sql(
table_name,
con=engine,
schema='staging',
if_exists='replace',
index= False,
method= 'multi'
)
print('imported data to staging.{}'.format(table_name))
with open('/home/kyle/projects/data_pipelines/ahc/sql/etl_{}.sql'.format(table_name)) as fp:
etl = fp.read()
result = engine.execute(etl)
print('moved {} rows to public.{}'.format(result.rowcount, table_name))
当我手动运行 .sql 脚本时,它们运行良好。我什至尝试制作存储过程,但这也不起作用。这是我正在执行的其中一个 sql 文件的示例:
--Delete Id's in prod table that are in current staging table
DELETE
FROM public.table
WHERE key IN
(SELECT key FROM staging.table);
--Insert new/old id's into prod table and do any cleaning
INSERT INTO
public.table
SELECT columna, columnb, columnc
FROM staging.table;
【问题讨论】:
-
或许可以试试
cnxn = engine.raw_connection(); cnxn.autocommit = True; crsr = cnxn.cursor(); crsr.execute(etl) -
不。没用。
-
TL;来自欺骗目标的 DR:您的 SQL 文件不是以 SQLA 识别为 DDL / DML 的内容开头(而是以注释开头),因此它不会自动提交。
-
谢谢你这样做。如果您想将其输入为答案,请标记它。
标签: python postgresql sqlalchemy