简体   繁体   English

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

[英]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. 我正在尝试遍历MySQL查询,但是我无法使变量正常工作。 What am I doing wrong? 我究竟做错了什么? The loop starts at line 10. 循环从第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 文件“ james_test.py”,第114行,位于“''中,(i))文件“ /usr/lib64/python2.7/site-packages/MySQLdb/cursors.py”,行187,在执行查询=查询%元组([args中的项目的db.literal(item)])TypeError:“ int”对象不可迭代

cur.execute expect a tuple o dict for params but you gave (i) which is an int not a tuple . cur.execute期待一个tuple Ô dict为PARAMS,但你给(i)这是一个int不是一个tuple To make it a tuple add a comma (i,) 要使其成为tuple添加逗号(i,)

Here's how I would do this. 这就是我要怎么做。 You may not need to declare 2 cursors, but it won't hurt anything. 您可能不需要声明2个游标,但这不会造成任何伤害。 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. 一种是带有fetchall,另一种是通过循环光标。 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. 另外请注意,只有1个参数时,需要在参数列表中使用结尾逗号。 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. 如果您有多个参数,则不需要尾部逗号,因为一个以上的parm将是一个元组。

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的“ .format”函数

Python string formatting: % vs. .format Python字符串格式:%vs.format

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM