MySQL Connector/Python - 将python变量插入MySQL表

use*_*354 9 python mysql insert mysql-connector-python

我正在尝试将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()
Run Code Online (Sandbox Code Playgroud)

这会得到错误

ProgrammingError: Failed processing pyformat-parameters; 'MySQLConverter' object has no attribute '_float64_to_mysql'
Run Code Online (Sandbox Code Playgroud)

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

mtr*_*ean 22

假设您正在使用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)
Run Code Online (Sandbox Code Playgroud)


小智 5

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