如何使用Python将NULL数据插入MySQL数据库? [英] How can I insert NULL data into MySQL database with Python?

查看:725
本文介绍了如何使用Python将NULL数据插入MySQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从Python脚本向MySQL插入一些数据时,出现一个奇怪的错误.这基本上与我要插入的变量为空有关.我认为MySQL不喜欢空白变量,但还有其他我可以将其更改为可以与我的insert语句一起使用的东西吗?

I'm getting a weird error when inserting some data from a Python script to MySQL. It's basically related to a variable being blank that I am inserting. I take it that MySQL does not like blank variables but is there something else I can change it to so it works with my insert statement?

如果空白,我可以成功地使用IF语句将其设置为0,但这可能会弄乱我计划稍后在MySQL中进行的某些数据分析.有没有办法将其转换为NULL或其他使MySQL接受但不添加任何内容的方法?

I can successfully use an IF statement to turn it to 0 if its blank but this may mess up some of the data analytics I plan to do in MySQL later. Is there a way to convert it to NULL or something so MySQL accepts it but doesn't add anything?

推荐答案

快速检查是否为空,如果为空,则将其设置为NULL:

Do a quick check for blank, and if it is, set it equal to NULL:

if(!variable_to_insert)
    variable_to_insert = "NULL"

...然后确保插入的变量不在insert语句的引号中,例如:

...then make sure that the inserted variable is not in quotes for the insert statement, like:

insert = "INSERT INTO table (var) VALUES (%s)" % (variable_to_insert)
...

不喜欢:

insert = "INSERT INTO table (var) VALUES ('%s')" % (variable_to_insert)
...

这篇关于如何使用Python将NULL数据插入MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆