Search code examples
mysqlpymysql

Can't insert None into mysql int field


I need to insert an int or None into a MySql int field (which is nullable). This is my code:

cur = db.cursor()
contents = [None, 3]
for element in contents:
    print(element)
    cur.execute('insert into test.new_test (blubb) values (%s)', element)
db.commit()

When I don't use None, but another int, this works. I just don't understand, why None does not work, I get the error

pymysql.err.ProgrammingError: (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"),

despite all of the solutions that I found for this saying that %s is able to handle None...
Also, is there maybe a way to add the entire list at once (a new row for each entry) without using a for loop?


Solution

  • In mysql it should be NULL so you need to change it to:

    cur = db.cursor()
    contents = ['NULL', 3]
    for element in contents:
        print(element)
        cur.execute('insert into test.new_test (blubb) values (%s)', element)
    db.commit()
    

    EDIT

    To solve the new isue you can change it to:

    cur = db.cursor()
    contents = [None, 3]
    for element in contents:
        print(element)
        if element==None:
            cur.execute('insert into test.new_test (blubb) values (NULL)')
        else:
            cur.execute('insert into test.new_test (blubb) values (%s)', element)
    db.commit()
    

    Another way is to change the strict mode like it explains here