在循环中执行 SQL 的 Python 脚本

标签 python pymysql

我正在尝试编写调用 mysql SQL 的 python 脚本。

我依靠第一个查询结果来运行第二个查询。问题是它抛出错误。

错误:cursor2.execute(field_sql,id)

import boto3
import importlib
import psutil
import pymysql
import pymysql.cursors
import subprocess
import sys

rdsConn = pymysql.connect(host = 'XXXX'),
                          db = 'XXXX',
                          user = 'XXXX',
                          password = 'XXXX',
                          charset = 'utf8mb4',
                          cursorclass=pymysql.cursors.DictCursor)

cursor1 = rdsConn.cursor()
cursor2 = rdsConn.cursor()


name = 'Test'
sql = "select id from Table1 where name = %s"
cursor1.execute(sql,name)
result = cursor1.fetchall()
for id in result:
    field_sql= "select columnname from  Table2 where id = %s"
    cursor2.execute(field_sql,id)
    fieldresult = cursor2.fetchall()
    for fieldrow in fieldresult:
        print(fieldrow)

cursor1.close()
cursor2.close()
rdsConn.close()

最佳答案

您的查询使用字典游标,因此它将返回字典列表,例如:

[{'id': 1}, {'id': '2'}, ...]

这意味着您的 id* 将是一个字典,而不是一个元组。这意味着您将参数作为字典传递给第二个查询。如果这样做,则需要使用 pyformat 样式来使用命名参数:

for rowdict in result:
    field_sql = "select columnname from  Table2 where id = %(id)s"
    cursor2.execute(field_sql, rowdict)
    fieldresult = cursor2.fetchall()
    for fieldrow in fieldresult:
        print(fieldrow)

您会看到打印的 fieldrow 也是 dict

此外,查询参数应作为字典(命名参数)或元组(位置参数)传递。 pymysql 接受 cursor.execute(sql, "name") 形式,其他 dbapi2 连接器不接受。规范形式为 cursor.execute(sql, ("name",))

*btw,您不应该使用 id 作为名称,它隐藏了内置的 id 函数

关于在循环中执行 SQL 的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44323142/

相关文章:

python pymysql.err.OperationalError : (2013, 'Lost connection to MySQL server during query' )

python - PyMySQL:插入数据准备语句

python - 如何使用 Flask/gunicorn 处理 Broken pipe 错误?

python - 如何在 Redhat Linux 上安装 pip

python - 从 C++ 中在本地范围内创建 Python 对象

python - 似乎无法让 Python、Peewee、pymysql 和 MySql 数据库正常工作,没有 'returning_clause' 错误

python - 如何忽略pymysql警告?

python - 使用重复的键属性序列化 NDB 模型

python - 从 PIL(Python 图像库)中的文件路径创建缩略图时如何修复这些错误

python - PyMySQL 选择不工作