You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何向MySQL查询传参并将查询结果写入CSV文件

问题解决方法

1. 解决SQL语法1064报错问题

报错的核心原因是你定义了带%s占位符的SQL语句,但执行cursor.execute()时没有传入对应的参数值。mysql-connector的参数传递规则如下:

  • 占位符%s不需要加引号,驱动会自动处理类型转义
  • 执行时需给execute方法传入第二个参数,格式为参数组成的元组,哪怕只有一个参数也要保留末尾的逗号,避免被识别为单个变量
    你需要修改的代码:
# 原来的错误写法
# cursor.execute(sqlSelect)
# 修正后的写法,传入account参数组成的元组
cursor.execute(sqlSelect, (account,))

可选优化:SQL语句外层的括号没有实际作用,可以直接写成sqlSelect = "Select * from AB where account = %s"

2. 解决CSV只写表头无数据问题

问题出在你调用了两次cursor.fetchall():

  • 第一次调用myresult = cursor.fetchall()时,已经把MySQL返回的全部结果集从游标中读取完毕,游标位置已经移动到结果末尾
  • 第二次调用results = cursor.fetchall()时,已经没有剩余数据可以读取,得到的是空列表,写入CSV自然没有数据
    你只需要删掉重复的fetchall调用,直接用第一次拿到的myresult写入CSV即可,修改代码:
# 删掉这行重复的读取代码
# results = cursor.fetchall()
# 写入时用第一次拿到的myresult
csvFile.writerows(myresult)

可选优化:打开CSV文件时添加newline=''参数,避免跨平台时出现多余空行,写法为openfile = open(filePath + file, 'w', newline='', encoding='utf-8'),同时可以显式指定编码避免乱码。

修正后的完整核心代码示例

import mysql.connector
import csv
import argparse

filePath = '/home/'
file = 'test.csv'

def main(account: str):
    cnxm = mysql.connector.connect(option_files='........')
    print('variable value is', account)
    cursor = cnxm.cursor()
    sqlSelect = "Select * from AB where account = %s"
    # 传入参数执行SQL
    cursor.execute(sqlSelect, (account,))
    myresult = cursor.fetchall()
    for x in myresult:
        print(x)
    print('Query ran successfully')
    headers = ['uuid']
    # 用with上下文管理自动关闭文件,避免资源泄漏
    with open(filePath + file, 'w', newline='', encoding='utf-8') as openfile:
        csvFile = csv.writer(openfile, delimiter=',', lineterminator='\r\n', quoting=csv.QUOTE_ALL, escapechar='\\')
        csvFile.writerow(headers)
        # 直接用第一次读取的结果写入
        csvFile.writerows(myresult)
    cursor.close()
    cnxm.close() # 新增关闭数据库连接,避免资源泄漏

def run() -> int:
    parser = argparse.ArgumentParser(
        description='Account',
        usage='python test.py --account XYZ1234'
    )
    parser.add_argument('-a', '--account', required=True, type=str, dest='account', help='account info')
    args = parser.parse_args()
    main(args.account)
    return 0

if __name__ == '__main__':
    exit(run())

内容的提问来源于stack exchange,提问作者atulgupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:45:02