insert NULL value in sybase database using python

旧巷老猫 提交于 2019-12-11 12:26:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!