我是python的新手。我有一个用例,在这个用例中,我必须解析CSV文件,然后必须将行插入到DB中。
以下是我的代码
with open(targetFileName, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
with conn.cursor() as cur:
cur.execute("insert into test (first, second) values(%s,%s)",row)
conn.commit()在这里,我逐行执行和提交查询。我想进行批量提交,而不是每一行都提交。有没有办法做到这一点?
发布于 2019-05-14 05:04:49
我还没有测试过它,但是你不能把for循环放在第二个with语句中,然后在for循环之后再提交吗?
with open(targetFileName, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
with conn.cursor() as cur:
for row in csvreader:
print(row)
cur.execute("insert into test (first, second) values(%s,%s)",row)
conn.commit()您还可以考虑在Psycopg2中使用execute_batch命令:
http://initd.org/psycopg/docs/extras.html#fast-execution-helpers
https://stackoverflow.com/questions/56117529
复制相似问题