Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
中的Python SQL单次提交与多次提交_Python_Sql_Insert_Pypyodbc - Fatal编程技术网

中的Python SQL单次提交与多次提交

中的Python SQL单次提交与多次提交,python,sql,insert,pypyodbc,Python,Sql,Insert,Pypyodbc,我是Python新手,所以我一直在根据我发现的内容整理脚本,并且进展顺利(也就是说,我的脚本即使不是最优雅或最正确的,也能正常工作)。我的最终目标是获取一个csv,读取它,找到一个阶段,然后如果找到该短语,将该行写入SQL数据库。我有这个工作,但我的问题是: 我应该在的每个循环中使用编写.execute(),然后使用编写.commit()(这就是我现在正在做的)?或者我应该构建一条语句并在最后执行/提交(不确定如何执行)?我通读了一遍,看到了如何设置插入的格式,但不确定如何使用我的代码(如下)并

我是Python新手,所以我一直在根据我发现的内容整理脚本,并且进展顺利(也就是说,我的脚本即使不是最优雅或最正确的,也能正常工作)。我的最终目标是获取一个csv,读取它,找到一个阶段,然后如果找到该短语,将该行写入SQL数据库。我有这个工作,但我的问题是:

我应该在
的每个循环中使用
编写
.execute()
,然后使用
编写
.commit()
(这就是我现在正在做的)?或者我应该构建一条语句并在最后执行/提交(不确定如何执行)?我通读了一遍,看到了如何设置插入的格式,但不确定如何使用我的代码(如下)并进行调整以构建具有多个值的单个插入。任何关于第一种方法的帮助或建议都很好,或者正确的方法是第二种方法就太好了!提前谢谢

背景:我正在使用pyodbc和一个VM。python脚本与SQL Express数据库位于同一个VM上

这是我的密码:

with open(CSVFILE, 'rt', encoding='utf8') as f:
    if debug:
        print('Inside the with')
    reader = csv.reader(f, delimiter=',')
    columns = next(reader)
    query = 'insert into TABLENAME ({0}) values ({1})'
    query = query.format(','.join(columns), ','.join('?' * len(columns)))
    for row in reader:
         for field in row:
             if data.strSearch in field:
                 if debug:
                     print('Found: {}'.format(row[0]))
                 cursor.execute(query, row)
                 cursor.commit()

尽管您可以将
.commit()
移动到循环之外,这样您在最后只执行一次提交,但您执行该操作的方式看起来很好。那可能会快一点


至于建议将行添加到列表中,然后使用
.executemany
,这种方法几乎总是会导致向服务器发送单独的INSERT语句,因此,它可能不会比将提交移到循环之外更能提高性能。

您可以将每个循环中感兴趣的
附加到另一个列表中,以提供嵌套列表。完成所有循环后,可以调用
executemany()
并传递行列表,而不是
execute()
,一次性插入记录,然后
commit()
更改。但是,在内部循环的每次迭代中使用
commit()。