如何使用Python将变量传递给MySQLdb查询?

时间:2015-12-11 07:15:25

标签: python mysql loops

我正在尝试遍历MySQL查询,但是我无法使变量起作用。我究竟做错了什么?循环从第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()

错误消息:

  

文件“james_test.py”,第114行,在''',(i))   文件“/usr/lib64/python2.7/site-packages/MySQLdb/cursors.py”,第187行,执行   query = query%tuple([db.literal(item)for args中的item])   TypeError:'int'对象不可迭代

3 个答案:

答案 0 :(得分:2)

cur.execute期望tuple o dict代表参数,但您提供的(i)int而不是tuple。要使其tuple添加逗号(i,)

答案 1 :(得分:1)

以下是我将如何做到这一点。你可能不需要声明2个游标,但它不会伤害任何东西。有时需要第二个游标,因为可能存在冲突。请注意我如何演示2种不同的循环游标数据的方法。一个带有fetchall,一个带有循环光标。第三种方法可以使用fetch,但未显示。使用字典光标非常好,但有时您可能希望使用标准的非字典光标,其中值仅通过行数组中的数字来检索。另请注意,只有1个参数时,需要在参数列表中使用尾随逗号。因为它期待一个元组。如果您有多个参数,则不需要尾随逗号,因为超过1个参数将是一个元组。

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"]

答案 2 :(得分:0)

也许试试这个:

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

你甚至可以这样做:

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

来源:

python's ".format" function

Python string formatting: % vs. .format