insert_statement = ("INSERT INTO mydb.sets_ledger "
"( exercise, weight, reps, rpe) "
"VALUES ( %(Exercise)s, %(weight)s, %(reps)s, %(rpe)s")
#import the CSV file
workout_file = "squat_rpe.csv"
file_hook = open(workout_file, 'rb')
dictionary=csv.DictReader(file_hook)
print dictionary.dialect
print dictionary.fieldnames
for row in dictionary:
print row['Day'], row['Exercise'], row['weight'], row['reps'], row['rpe']
print "==> "
cursor.execute(insert_statement, row)
当我从字典中输入一行时崩溃,其中一列(在本例中“rpe”列为空)。
row = {'rpe': '', 'weight': '60', 'reps': '3', 'Day': '04/26/14', 'Exercise': 'Competition Back Squat’}
给我最终错误
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
rpe、reps、weight的mysql模式都是十进制(10,5)
当数据周围散布着空值时,如何使用字典/参数方法生成 SQL 查询?
======================================
我构建了一个单独的测试:
import csv
import mysql.connector
#engage the MySql Table
cnx= mysql.connector.connect(user='root', host='127.0.0.1', database='mydb')
cursor = cnx.cursor()
insert_statement_dic = ("INSERT INTO mydb.sets_ledger "
"( exercise, rpe) "
"VALUES ( %(exercise)s, %(rpe)s)")
insert_statement_tuple = ("INSERT INTO mydb.sets_ledger "
"( exercise, rpe) "
"VALUES ( %s, %s)")
tuple_param_10 = ('tuple insert test 10', 10)
tuple_param_pure_none = ('tuple insert test None', None)
tuple_param_quoted_none = ('tuple insert test quoted none', 'None')
cursor.execute(insert_statement_tuple, tuple_param_10);
cursor.execute(insert_statement_tuple, tuple_param_pure_none);
#cursor.execute(insert_statement_tuple, tuple_param_quoted_none);
dic_param_10 = {'exercise': 'dic_param_10', 'rpe': 19}
dic_param_None = {'exercise': 'dic_param_None', 'rpe': None}
dic_param_quoted = {'exercise': 'dic_param_None', 'rpe': 'None'}
cursor.execute(insert_statement_dic, dic_param_10);
cursor.execute(insert_statement_dic, dic_param_None);
#cursor.execute(insert_statement_dic, dic_param_quoted);
cnx.commit()
cursor.close()
cnx.close()
要将“无值”(NULL)插入小数列,我需要插入 >None< not >''< 且 not >'None'<
这意味着,当我从逗号分隔值构建参数字典时,我需要执行一个清理函数,将任何空字符串 ('') 转换为 a _builtin.None 。 (除非我能找到某种方法让 CSV 模块自动将空字符串 ('') 转换为 None。
最佳答案
该错误与您的值为空无关,而是与您的查询中的错误有关。错误消息只是提示您查询中发生解析错误的位置,即在 ''
上。
如果您在查询后打印 cursor._execulated
,您会看得更清楚,它应该显示如下内容:
INSERT INTO ... VALUES ( ..., ''
正如您所看到的,真正的问题是您的查询缺少右括号,它应该是:
insert_statement = ("INSERT INTO mydb.sets_ledger "
"( exercise, weight, reps, rpe) "
"VALUES ( %(Exercise)s, %(weight)s, %(reps)s, %(rpe)s )")
关于python - mysql/python 连接器使用参数和字典在处理空值时死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313359/