1

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

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Pay careful attention to type in Python (depending on what lang you come from this may be a little weird). Use Pythons's type(var) - I have those statements all over early builds still. Also key is isinstance() to determine if is a type of string/class/etc or instance of specific class name.
@BK435 the advice is entirely use-case specific. The OP compares the result of the SQL query which returns an integer id with integer 1. There is no point in making an intermediate string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.