gpt4 book ai didi

python - 设置 %s 的 Mysqldb 更新错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:44 27 4
gpt4 key购买 nike

我已经用 MySQLdb 创建了一个数据库。
在数据库中,我有一个名为 student 的表,其中包含以下列:

id(is int),id_user(is int),f_name(is str),l_name(is str)

I want to update a row.
My code is below:

db=mdb.connect(host="localhost", use_unicode="True", charset="utf8", 
user="", passwd="", db="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()

sql="""SELECT id_user FROM student"""

try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

rows = cursor.fetchall()

the=int(7)
se=str('ok')
for row in rows:
r=int(row[0])
if r==the:
sql2 = """UPDATE student
SET f_name=%s
WHERE id_user = %s"""% (se,the)

# Execute the SQL command
cursor.execute(sql2)
# Commit your changes in the database
db.commit()

db.rollback()
# disconnect from server
db.close()

当我运行它时,我发现有一个名称为 ok 的列出现错误,为什么?
谁能帮我找到我做错了什么?

最佳答案

str 没有将其参数用引号引起来,因此您的语句是这样的:

UPDATE student SET f_name=ok WHERE id_user = 7

当需要时:

UPDATE student SET f_name='ok' WHERE id_user = 7

所以,要么改变这一行:

                SET f_name=%s

为此:

                SET f_name='%s'

或者改变这一行:

se=str('ok')

为此:

se="'" + str('ok') + "'"

虽然我建议阅读 SQL injection ,一旦您开始使用用户提供的数据而不是硬编码值,这就会成为一个问题。

关于python - 设置 %s 的 Mysqldb 更新错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9742846/

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