将一些数据从Python脚本插入MySQL时,我遇到了一个奇怪的错误.它基本上与我插入的变量空白有关.我认为MySQL不喜欢空白变量但是还有其他东西我可以改变它以便它适用于我的insert语句吗?
IF如果它的空白,我可以成功地使用一个语句将其变为0,但这可能会破坏我计划稍后在MySQL中执行的一些数据分析.有没有办法将它转换为NULLMySQL接受它但不添加任何东西?
小智 144
使用mysqldb时cursor.execute(),传递值None,而不是"NULL":
value = None
cursor.execute("INSERT INTO table (`column1`) VALUES (%s)", (value,))
Run Code Online (Sandbox Code Playgroud)
在这里找到答案
pha*_*ian -26
快速检查是否为空白,如果是,则将其设置为 NULL:
if(!variable_to_insert)
variable_to_insert = "NULL"
Run Code Online (Sandbox Code Playgroud)
...然后确保插入的变量不在插入语句的引号中,例如:
insert = "INSERT INTO table (var) VALUES (%s)" % (variable_to_insert)
...
Run Code Online (Sandbox Code Playgroud)
不喜欢:
insert = "INSERT INTO table (var) VALUES ('%s')" % (variable_to_insert)
...
Run Code Online (Sandbox Code Playgroud)