简体   繁体   中英

How to pass variable into MySQLdb query with Python?

I'm trying to loop over an MySQL query, however I can't get the variable to work. What am I doing wrong? The loop starts at line 10.

cur = db.cursor()
query = '''
Select user_id, solution_id 
From user_concepts
Where user_id IN 
  (Select user_id FROM fields);
'''    
cur.execute(query)
numrows = cur.rowcount
for i in xrange(0,numrows):
    row = cur.fetchone()
# find all item_oid where task_id = solution_id for first gallery and      sort by influence.
    cur.execute('''
        SELECT task_id, item_oid, influence
        FROM solution_oids 
        WHERE task_id = row[%d]
        ORDER BY influence DESC;
        ''', (i))
    cur.fetchall()

error message:

File "james_test.py", line 114, in ''', (i)) File "/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py", line 187, in execute query = query % tuple([db.literal(item) for item in args]) TypeError: 'int' object is not iterable

cur.execute expect a tuple o dict for params but you gave (i) which is an int not a tuple . To make it a tuple add a comma (i,)

Here's how I would do this. You may not need to declare 2 cursors, but it won't hurt anything. Sometimes a second cursor is necessary because there could be a conflict. Notice how I demonstrate 2 different methods for looping the cursor data. One with the fetchall and one by looping the cursor. A third method could use fetch, but is not shown. Using a dictionary cursor is really nice, but sometimes you may want to use a standard non-dict cursor where values are retrieved only by their number in the row array. Also note the need to use a trailing comma in the parameter list when you have only 1 parameter. Because it expects a tuple. If you have more than 1 parameter, you won't need a trailing comma because more than 1 parm will be a tuple.

cursor1 = db.cursor(MySQLdb.cursors.DictCursor)  # a dictcursor enables a named hash
cursor2 = db.cursor(MySQLdb.cursors.DictCursor)  # a dictcursor enables a named hash

cursor1.execute("""
    Select user_id, solution_id 
      From user_concepts
     Where user_id IN (Select user_id FROM fields);
"""    

for row in cursor1.fetchall():
    user_id = row["user_id"]
    solution_id = row["solution_id"]

    cursor2.execute("""
        SELECT task_id, item_oid, influence
        FROM solution_oids 
        WHERE task_id = %s
        ORDER BY influence DESC;
    """, (solution_id,))

    for data in cursor2:
        task_id = data["task_id"]
        item_oid = data["item_oid"]
        influence = data["influence"]

Maybe try this:

a = '''this is the {try_}. try'''
i= 1    
b = a.format(try_=i)
print b

You could even do:

data = {'try_':i}
b = a.format(**data)

sources:

python's ".format" function

Python string formatting: % vs. .format

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