【问题标题】:pymysql: How to format types on query?pymysql:如何在查询中格式化类型?
【发布时间】:2016-08-16 07:29:36
【问题描述】:

我正在尝试使用 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,但我仍然不清楚我应该怎么做。有什么建议吗?

【问题讨论】:

    标签: python mysql python-3.x pymysql


    【解决方案1】:

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

    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()
    

    还有那个executemany() method:

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

    【讨论】:

    • "%s" 不是字符串?如何处理日期和整数?
    • @lithiium mysql 驱动程序本身应该在您进行参数化查询时处理类型转换。
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2014-08-25
    • 2021-08-28
    • 2014-03-08
    • 2015-03-05
    • 2023-01-21
    • 1970-01-01
    • 2015-04-16
    相关资源
    最近更新 更多