首页 > 解决方案 > 如何在 Python 中将参数传递给 SQL 查询并将结果写入 csv 文件

问题描述

我正在尝试将运行时参数传递给 Python 脚本中的 MYSQL 查询。我正在使用 python 3.7.3。我收到以下代码错误。

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 

我试图了解如何将参数值传递给 sql 查询。另一个问题是它不会将记录写入 .csv 文件。它只创建文件并向文件添加标题

这是我的示例代码:

# File to store data from SQL
filePath = '/home/'
file = 'test.csv'



def main(account: str):

    # Staging Security
    cnxm = mysql.connector.connect(option_files='........)

    print('variable value is', account)

    # Cursor to execute query.
    cursor = cnxm.cursor()

    sqlSelect = """(Select * from AB where account = %s)"""


    # Execute query.
    cursor.execute(sqlSelect)

    myresult = cursor.fetchall()

    for x in myresult:
        print(x)

    print('Query ran successfully')

    # Fetch the data returned.
    results = cursor.fetchall()


    # Extract the table headers.
    #headers = [i[0] for i in cursor.description]
    headers = ['uuid']


    # Open CSV file for writing.
    openfile = open(filePath + file, 'w')
    csvFile = csv.writer(openfile, delimiter=',', lineterminator='\r\n', quoting=csv.QUOTE_ALL, escapechar='\\')

    # Add the headers and data to the CSV file.
    csvFile.writerow(headers)
    csvFile.writerows(results)



    #Close file
    openfile.close()

    #Close cursor
    cursor.close()

def run() -> str:
    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())

我使用以下命令运行我的脚本:python3 test.py -a ABC123XY

请帮忙。先感谢您。

标签: python-3.xmysql-python

解决方案


推荐阅读