开发者

SQLite no return type in Python

I am trying to find a way to know whether or not some value was returned from an SQLite query when using python.

conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
cursor.execute("select field from table where other_field = ?", t)
returnObject = cursor.fetchone()[0]

If the table does contain a matching value, then it will be stored in returnObject.

The problem happens in the case that the database doesn't have any entries matching the request. In that case, I get a exceptions.TypeError: unsubscriptable 开发者_如何转开发object

Besides placing this entire block in a try/expect block, is there a way of knowing whether or not something was returned by the database.

Also, I am aware that I could issue an extra query, but this would make the connection too chatty.


You have a couple options, depending on your preferences.

Option 1: check the value of returnObject before using it.

conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
cursor.execute("select field from table where other_field = ?", t)
returnObject = cursor.fetchone()
if returnObject:
    print returnObject[0]
else:
    print "Nothing found!"

Option 2: use the return value of execute(). It contains the number of rows in the result.

conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
rowCount = cursor.execute("select field from table where other_field = ?", t)
if rowCount > 0:
   returnObject = cursor.fetchone()[0]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜