问题
Let's say we have the following sql statement:
INSERT INTO myTable VALUES (1,"test")
In my python code the first value is either an integer or NULL. How can I insert NULL value using python code?
Code snippet:
var1 = getFirstValue()
var2 = getSecondValue()
qry = "INSERT INTO myTable VALUES (%d,%s)" % (var1,var2)
Whenever var1 is None it is throwing error, but I want NULL to be inserted.
回答1:
You can use:
qry = "INSERT INTO myTable VALUES ({0}, {1})".format(var1, var2)
回答2:
Since you marked this question with the tag Django, you must be aware that you don't just write queries and save them in the Database, Django handles this.
Just check the Tutorial that is available here : https://docs.djangoproject.com/en/1.6/intro/tutorial01/
Since you mentioned Sybase, you must get the Django driver from (https://github.com/sqlanywhere/sqlany-django) and modify the DATABASES entry inside your settings.py project. (first finish the tutorial)
回答3:
Here is one possible option:
var1 = getFirstValue()
var2 = getSecondValue()
var2 = "'{0}'".format(var2) if var2 is not None else 'NULL'
qry = "INSERT INTO myTable VALUES ({0},{1})".format(var1,var2)
来源:https://stackoverflow.com/questions/20899894/insert-null-value-in-sybase-database-using-python