PyMySQL Insert NULL or a String

Cronos87 picture Cronos87 · Feb 24, 2015 · Viewed 18.1k times · Source

I tried to insert a field (title) with PyMySQL that can be NULL or a string. But it doesn't work.

query = """
    INSERT INTO `chapter` (title, chapter, volume)
    VALUES ("%s", "%s", %d)
"""

cur.execute(query % (None, "001", 1))
cur.execute(query % ("Title", "001", 1))

This code inserts None into the database. If I remove the double quote around the first %s, it throws an error:

pymysql.err.InternalError: (1054, "Unknown column 'None' in 'field list'")

What can I do to insert NULL?

Answer

Retard picture Retard · Feb 24, 2015

1) Never use string formatting for SQL.

2) Try the following:

query = """
INSERT INTO `chapter` (title, chapter, volume)
VALUES (%s, %s, %s)
"""
cur.execute(query, (None, "001", 1))