gpt4 book ai didi

python - Python MySQL 连接器中的变量在函数中不起作用

转载 作者:行者123 更新时间:2023-11-29 15:12:31 25 4
gpt4 key购买 nike

我已经创建了一个函数来整理我将在程序中执行的 SQL 调用。通常这会起作用

mycursor = mydbr.cursor()
mycursor.execute("SELECT song FROM charts WHERE artist=%s",(artist,))
x = mycursor.fetchone()

我的函数看起来像这样

import mysql.connector
def SqlQuery(connection, query, forvar1 = None, forvar2 = None):
sqlobj = connection.cursor()
if forvar1 is None and forvar2 is None:
sqlobj.execute(query)
if forvar1 is not None and forvar2 is None:
sqlobj.execute(query, forvar1)
if forvar1 is not None and forvar2 is not None:
queryvars = (forvar1,forvar2)
sqlobj.execute(query % queryvars)
result = sqlobj.fetchone()
connection.commit
return result

查询列表

sql = ["SELECT song FROM charts WHERE artist=%s"]

我的函数调用如下所示

record = SqlQuery(mydbr, sql[0], artist)

但是每当它运行时,它就会完全错过添加变量,我已经观察了通过wireshark发送的内容,看起来像

SELECT song FROM charts WHERE artist=%s

任何帮助都会很棒

最佳答案

该死的,我尝试了很多变体,但这个网站有正确的一个

https://pynative.com/python-mysql-select-query-to-fetch-data/

sqlobj.execute(query, forvar1)

应该是

sqlobj.execute(query, (forvar1,))

关于python - Python MySQL 连接器中的变量在函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59959111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com