简体   繁体   中英

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM