我试图使用pymysql(Python 3)在MySQL表上插入行,相关代码如下。

def saveLogs(DbConnection, tableName, results):
    for row in results:
        formatStrings = ",".join(["?"]*len(row))
        sql = "INSERT INTO %s VALUES (%s);"%(tableName,formatStrings)
        DbConnection.cursor().execute(sql, tuple(row))
    DbConnection.commit()

我使用"?"作为类型,但是我得到了错误not all arguments converted during string formattingrow是由strings、ints和datetime.datetime组成的列表。我想问题出在"?"上,但是我已经检查了PEP 249,我还不清楚该怎么做。有什么建议吗?

最佳答案

仅对表名使用字符串格式(不过,请确保您信任源或具有适当的验证)。对于其他所有内容,请使用查询参数:

def saveLogs(DbConnection, tableName, results):
    cursor = DbConnection.cursor()
    sql = "INSERT INTO {0} VALUES (%s, %s, %s)".format(tableName)
    for row in results:
        cursor.execute(sql, row)
    DbConnection.commit()

还有一点是:
def saveLogs(DbConnection, tableName, results):
    cursor = DbConnection.cursor()
    cursor.executemany("INSERT INTO {0} VALUES (%s, %s, %s)".format(tableName), results)
    DbConnection.commit()

10-06 02:14