10

我正在尝试将 python 变量插入到 python 脚本中的 MySQL 表中,但它不起作用。这是我的代码

add_results=("INSERT INTO account_cancel_predictions"
            "(account_id,21_day_probability,flagged)"
            "Values(%(account_id)s,%(21_day_probability)s,%(flagged)s)")

data_result={
    'account_id':result[1,0],
    '21_day_probability':result[1,1],
    'flagged':result[1,2]
}

cursor.execute(add_results,data_result)

cnx.commit()
cursor.close()
cnx.close()

这会得到错误

ProgrammingError: Failed processing pyformat-parameters; 'MySQLConverter' object has no attribute '_float64_to_mysql'

但是,当我用它们的实际数值替换变量名result[1,0],result[1,1]和时,它确实有效。result[1,2]我怀疑 python 传递的是实际的变量名,而不是它们持有的值。我该如何解决?

4

3 回答 3

24

假设您正在使用mysql.connector(我认为您是),请定义您自己的转换器类:

class NumpyMySQLConverter(mysql.connector.conversion.MySQLConverter):
    """ A mysql.connector Converter that handles Numpy types """

    def _float32_to_mysql(self, value):
        return float(value)

    def _float64_to_mysql(self, value):
        return float(value)

    def _int32_to_mysql(self, value):
        return int(value)

    def _int64_to_mysql(self, value):
        return int(value)

config = {
    'user'    : 'user',
    'host'    : 'localhost',
    'password': 'xxx',
    'database': 'db1'
}

conn = mysql.connector.connect(**config)
conn.set_converter_class(NumpyMySQLConverter)
于 2013-10-21T19:13:49.983 回答
7

您传递的值之一可能是numpy.float64MySQL 连接器无法识别的类型。float在填充字典时将其转换为真正的蟒蛇。

于 2013-07-09T22:49:07.107 回答
0

如果您使用的是 python 3 及更高版本,只需使用 mysqlclient pip install mysqlclient。这是 django 推荐的,所有其他驱动程序都不好。

于 2018-02-19T18:32:58.637 回答