Python, Mysql, insert NULL

Laszlo Zsolt Nagy gandalf at designaproduct.biz
Wed Oct 5 07:11:28 EDT 2005


Python_it wrote:

>Python 2.4
>MySQL-python.exe-1.2.0.win32-py2.4.zip
>
>How can I insert a NULL value in a table (MySQL-database).
>I can't set a var to NULL? Or is there a other possibility?
>My var must be variable string or NULL.
>Becaus i have a if statement:
>if ....
>  cursor.execute(".................insert NULL ..............")
>if ....
>  cursor.execute(".................insert "string" ..............")
>
>  
>
Use parameters! For example, did you try:

cursor.execute(" insert into tablename(fieldname) values (%s)",[value])

None will be converted to NULL, any other value will be quoted as neccesary.

BTW, you did not write which driver are you using.
Usage of parameters is different for each driver, but it is standardized.
If it is DB API 2.0 compatible, then parametrized queries should work as 
desicribed in PEP 0249:

http://www.python.org/peps/pep-0249.html

Under 'cursor objects' section, look for the '.execute' method.



More information about the Python-list mailing list