简体   繁体   中英

Set python variable from result of SQL query

I am playing with python for the first time on the raspberry pi.

I have a script that queries an SQL table and returns the value that is set.

What I can not get to work is setting the python variable from the results.

Here is part of the code I have

# execute SQL query using execute() method.
cursor.execute("select id from wallboard")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()

# disconnect from server
db.close()

result = str("%s " % data)
print result

if result == 1:

The print displays the result okay but it is not going into the if statement.

I am very new to python so its possibly a simple fix but I'm stumped.

Thanks

Don't convert the result to string:

>>> "1" == 1
False

Also note that fetchone() would return you a single row of results which would be represented as a tuple - get the first item to get the actual id column value:

result = 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