Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python MySQL insert NULL (None) value error

Tags:

python

null

mysql

I am trying to insert a NULL value into a MySQL db int field with a python script. NOT NULL is off on the field so its not that. I have manually inserted a NULL value into database and that worked fine and my code works fine if I put a literal value in the place of None.

I have looked a several people's examples of how to do this and as far as I can tell there is nothing wrong in syntax.

Code:

length2 = None

cursor.execute("INSERT INTO tableName(Length) VALUES(%s)", length2)

Error:

Error 1064: 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 
'%s)' at line 1

Any ideas?

like image 298
user1415944 Avatar asked Feb 11 '26 01:02

user1415944


1 Answers

The second argument to execute() should be a tuple (or list).
Please change your code to:

cursor.execute("INSERT INTO tableName (Length) VALUES (%s);", (length2,))
like image 96
mechanical_meat Avatar answered Feb 13 '26 17:02

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!