0

Can I use the results of a python SQL select query as parameters for an if/else statement in a function? If I have a DB with one column, and want to append the values of that column to a list for each row in the Select Query...I can't reference those queries in a function. For example:

db = MySQLdb.connect(host="localhost", user="root", passwd="****", db="****")
cur = db.cursor()

selectArray1 = []
cur.execute("SELECT * FROM tableName WHERE value = 'x'")
for row in cur.fetchall():
    selectArray1.append(str(row[0]))


selectArray2 = []
cur.execute("SELECT * FROM tableName WHERE value = 'y'")
for row in cur.fetchall():
    selectArray2.append(str(row[0]))

def function(x):
    #----Question-----
    #if I try to print out selectArray1[x] or selectArray2[x], why don't I get
    # a return value?

    #Following conditionals do not work, why not?
    if selectArray1[x] == "some string":
        print "The first array equals the x query"

    if selectArray2[x] == "different string":
        print "The second array equals the y query"

if __name__ == '__main__':
    function(1)
    function(2)
1
  • Why not use the ORM in your code? for example you can use dataset library in your code Commented Oct 4, 2016 at 14:59

1 Answer 1

0

Please see this link: Convert sql result to list python

Basically, you want something similar to this:

list(cur.fetchall())

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response, but doesn't this "list(cur.fetchall())" simply add the fetched row into a list? That is not my issue. My problem is that I can't reference an element that I already have in a list inside of a function.
Have you tried my correction? I assume your issue is that selectArray1.append(str(row[0])) only ever adds the 0th index, while my code should copy the entire list.

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.