批量插入mysql数据库

def _write(self):
    rows = []
    while True:
        row = self._queue.get()
        if row is None:
            break
        rows.append(row)
        if len(rows) == self._batch:
            self._execute_many(rows)
            rows = []
    if rows:
        self._execute_many(rows)
    self._conn.commit()

def _execute_many(self, rows):
    with self._conn.cursor() as cursor:
        fields = self._fields
        table = self.table
        sql = """INSERT INTO `{table}` ({field}) VALUES ({mark})""".format(
            field='`' + '`, `'.join(fields) + '`',
            mark=', '.join(['%s'] * len(fields)),
            table=table
        )
        cursor.executemany(sql, rows)

猜你喜欢

转载自blog.csdn.net/sxf_123456/article/details/82151277