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?
Retard
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))
yangh
Change your code like this:
query = """INSERT INTO chapter(title, chapter, volume) VALUES (%s, %s, %s)"""
cur.execute(query, (None, "001", 1))
connection.commit()
来源:https://stackoverflow.com/questions/28698722/pymysql-insert-null-or-a-string