Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 317
Cronos87 Avatar asked Feb 24 '15 14:02

Cronos87


People also ask

How do I insert a null value into a date field?

"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);

Is it better to store NULL or empty string?

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.

How do you insert a NULL in Python?

In python NULL equivalent is None. So, specify None for the records which you wish to insert as NULL values as shown below.

Can we insert null value in Oracle?

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 Answers

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))
like image 110
Retard Avatar answered Sep 17 '22 07:09

Retard