文件的PostgreSQL COPY结果为空表

时间:2018-10-13 07:48:03

标签: python postgresql sqlalchemy

我正在使用以下代码将数据从.csv文件复制到表中

带标题的csv文件(逗号分隔):

uid,name,val1,val2,file
SKU001,glasses,blue,metal,block_0
...

创建表:

ih_sql = 'CREATE TABLE "sku_data" (uid VARCHAR, name VARCHAR, val1 VARCHAR, val2 VARCHAR, file VARCHAR, PRIMARY KEY (uid));'
engine.execute(ih_sql)
#<sqlalchemy.engine.result.ResultProxy at 0x7fee9b8ff550>

复制数据:

ih_file = os.path.abspath(f'{PATH}data.csv')
copy_sql = f"COPY sku_data FROM '{ih_file}' WITH CSV HEADER DELIMITER ','"
engine.execute(copy_sql)
#<sqlalchemy.engine.result.ResultProxy at 0x7fee9b8ff710>

但是,结果表为空,将创建零行。我怎么知道为什么没有从csv文件复制任何数据?

1 个答案:

答案 0 :(得分:2)

您必须明确提交交易,例如:

copy_sql = f"COPY sku_data FROM '{ih_file}' WITH CSV HEADER DELIMITER ','"
connection = engine.connect()
with connection.begin():
    connection.execute(copy_sql)

详细了解Understanding Autocommit.