python - 将参数值插入 MySQLdb.execute() 时出现问题

标签 python mysql mysql-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()

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

为什么我的代码打印一个空元组?

最佳答案

Python 的字符串格式运算符 % 不够智能,无法为 MySQL 引用参数 - 将参数传递给数据库 execute 函数,该函数会将参数传递给 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?

关于python - 将参数值插入 MySQLdb.execute() 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24345868/

相关文章:

php - FreeBSD PHP 执行权限被拒绝

python - 如何在 Docker 上运行的 Apache Superset 中为电子邮件报告配置 Celery Worker 和 Beat?

python - django.core.exceptions.ImproperlyConfigured : Error loading MySQLdb module:

python - 我如何从 Python 中检测到 MySQL 服务器的总死亡?

python组/用户管理包

python - 在 python/pandas 中转置列

python - 在共享主机中安装 MySQL-python

mysql:使用 COALESCE 以逗号分隔格式选择多个行值

mysql - 如何在 InnoDB 中构建这样一个将下划线视为单独单词的全文索引?

python - 在不安装Mysql的情况下使用python连接MySQL