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

发布于 2021-01-29 17:14:59

我正在尝试将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正在传递实际的变量名称,而不是它们所持有的值。我该如何解决?

关注者
0
被浏览
145
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    假设您正在使用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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看