Cronos87 Cronos87 - 1 year ago 518
MySQL Question

PyMySQL Insert NULL or a String

I tried to insert with PyMySQL a field (title) that's 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 insert None in the database. If I remove the double quote around the first %s, it throw an error:

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

How can I do to insert NULL?

Answer Source

1) Never use string formatting for sql

2) try

query = """
INSERT INTO `chapter` (title, chapter, volume)
VALUES (%s, %s, %s)
cur.execute(query, (None, "001", 1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download