python-3.x - 如何在 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
请帮忙。先感谢您。
解决方案
推荐阅读
- swift - 比较两个日期 - Swift
- datetime - 我如何在颤动中像这样 2019-07-08T10:37:28Z 格式化日期
- java - 如何从 Internet 上的某些资源中读取信息并将其保存在数据库中
- oracle - Flyway 不支持 PL/SQL 内联函数?
- longitudinal - 如何在多级回归代码中包含日记数据/滞后数据
- python - 大多数pythonic尝试的方式,除了,重试一次
- angular - 创建自定义验证器以针对多个表单字段进行验证
- c++ - 具有前向声明的共同依赖 .h 文件
- html - 尝试在 Bootstrap 4 中扩展行的宽度
- javascript - 我可以找到关于可编辑内容的插入符号位置吗?当我按下回车键并开始写作时,它会给出关于新 div 的插入符号位置