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