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?
"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);
So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.
In python NULL equivalent is None. So, specify None for the records which you wish to insert as NULL values as shown below.
The simplest way to put NULL into any column, regardless of the datatype, is: INSERT INTO emp (hiredate) VALUES (NULL); Don't use single-quotes around NULL. Putting it in single-quotes makes it a 4-character string value.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With