我目前正试图加快通过第三方工具传输数据的过程。我编写了一个函数,将insert语句批量推送到mysql数据库中,但出现以下错误:
_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
我编写的函数如下,包括record_array(包含要推送到mysql表的数据的dict数组)和tablename(包含表名的字符串):
def insert_update_bulk(self, record_array, tablename):
session = self.Session()
self.merge_query = ""
for r in record_array:
query = '''INSERT INTO {} ('''.format(tablename)
for k in r.keys():
query += '{}, '.format(k)
query = query[:-2] + ''') VALUES ('''
for v in r.values():
if type(v) == int:
query += '{},'.format(v)
else:
query += '"{}",'.format(str(v).replace('"', "'").replace('\n', ' ').replace('\r', ' '))
query = query[:-1] + ''') ON DUPLICATE KEY UPDATE '''
for k in r.keys():
if type(r[k]) == int:
query += '{}={},'.format(k, str(r[k]).replace('"', "'")).replace("'None'", 'NULL')
else:
query += '{}="{}",'.format(k, str(r[k]).replace('"', "'")).replace("'None'", 'NULL')
query = query[:-1] + '; '
self.merge_query += query
session.execute(self.merge_query.replace('%', '%%'))
self.Session.close_all()
暂无答案!
目前还没有任何答案,快来回答吧!