python在mysql中插入bulk时出现“命令不同步”错误

uxhixvfz  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(153)

我目前正试图加快通过第三方工具传输数据的过程。我编写了一个函数,将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()

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题