Search code examples
pythonmysqlpymysql

PyMySQL Insert NULL or a String


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?


Solution

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