Python, Mysql, insert NULL

Thomas Bartkus thomasbartkus at comcast.net
Wed Oct 5 16:15:15 EDT 2005


"Python_it" <python_it at hotmail.com> wrote in message
news:1128511466.880413.158140 at g49g2000cwa.googlegroups.com...
> 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!

MySQL accepts and understands the keyword "Null" directly.
When you list your VALUE parameters in an INSERT statement, a null is simply
the string "Null".
Don't quote the word "Null" inside your sql statement, MySQL understands it
directly. If you do quote it, MySQL will think you are talking about a
string value that happens to be spelled "N u l l"

Your sql string needs to end up looking something like this -
sql = "INSERT INTO SomeTable (This, That, TheOther) VALUES (3, 12, Null)"
   or
sql = "UPDATE sometable SET TheOther=Null WHERE something =
SomeThingOrOther"
   before you
cursor.execute(sql)

Notice that the MySQL keyword "Null" stands naked within each string.

Others here have pointed out that the Python keyword "None" is converted to
"Null" when passed to MySQL. I don't quite understand this and don't really
care.  If I have a Python variable that has a value None, and I want to
transmit this to MySQL as Null - I would:

   if somevar == None:
       StrToConcatenateIntoSqlStatement = "Null"
   else:
       StrToConcatenateIntoSqlStatement = somevar

All of which assumes, of course, that the field you are targeting will
accept a Null value.
Thomas Bartkus





More information about the Python-list mailing list