How can I insert NULL data into MySQL database with Python?

后端 未结 4 1751
北荒
北荒 2020-12-03 00:16

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 MyS

4条回答
  •  执念已碎
    2020-12-03 01:18

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

    if(!variable_to_insert)
        variable_to_insert = "NULL"
    

    ...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)
    ...
    

    not like:

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

提交回复
热议问题