Python, Mysql, insert NULL

Gerhard Häring gh at ghaering.de
Wed Oct 5 08:26:46 EDT 2005


Python_it wrote:
> I know how to insert values in a database.
> That's not my problem!
> My problem is how i insert NULL values in de mysql-database.
> None is een object in Python and NULL not.
> None is not converted to NULL?
> Table shows None and not NULL!

As Laszlo wrote, "None will be converted to NULL" for the Python => SQL 
direction. And also, NULL will be converted to None for SQL => Python 
direction.

And to avoid unneccessary if-then-else you should follow his advice and 
use parametrized queries. I. e.

cursor's execute method has two parameteres:

1) SQL query with placeholders
2) parameters

For example:

var1 = "Joe's dog"
cur.execute("insert into mytable(col1) values (%s)", (var1,))
var1 = None
cur.execute("insert into mytable(col1) values (%s)", (var1,))

if you use MySQLdb (the most sensible choice for a MySQL Python database 
adapter).

Because MySQLdb uses the pyformat param style, you use the %s 
placeholder always, no matter which type your parameter will be.

Also, the tip to read the DB-API specification 
http://www.python.org/peps/pep-0249.html is a good one in my opinion.
It really pays off to learn how to do things the DB-API way.

HTH,

-- Gerhard




More information about the Python-list mailing list