将参数值插入MySQLdb.execute文件()

2024-09-29 23:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码执行一个查询,然后对结果集中的每一行尝试使用该行中的值执行另一个查询。你知道吗

import MySQLdb as mdb
try:
    con = mdb.connect('localhost', 'root', '', 'cccorder_uk');

    with con:
        cur = con.cursor()
        cur.execute("SELECT code, name, box_size, commodity_code, country_of_origin FROM cccorder_uk.stocks")
        rows = cur.fetchall()
        for row in rows:
            # split the code and take colour and size

            code = row[0].split('-')
            product_code = code[0]

            sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='%s'""" % (product_code,)

            cur.execute(sql)
            results = cur.fetchall()
            print results

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)

finally:    

    if con:    
        con.close()

当我打印results时,我得到一个空元组,但是如果我硬编码product_code,例如sql = """SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style='EP22'""",这将返回我期望的结果。你知道吗

为什么我的代码打印一个空元组?你知道吗


Tags: namefrommapsqlstockcodeproductcon
1条回答
网友
1楼 · 发布于 2024-09-29 23:22:22

Python的字符串格式操作符%不够聪明,无法引用MySQL的args将args传递给数据库execute函数,该函数将args正确地传递给MySQL。你知道吗

示例:

cur.execute("SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style=%s", product_code)

见:How can I format strings to query with mysqldb in Python?

相关问题 更多 >

    热门问题