MySQL 用变量更新
我在更新表时遇到问题。 该代码来自电报机器人。我们正在收到用户的消息,并询问他的姓名。这是变量“first_name”。我们已经知道他的 user_id 是整数。 然后我尝试这样做
def bd_set(body):
cursor.execute(body)
connect.commit()
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},{first_name})")
并收到错误: 没有这样的列“John”。
但是,如果我尝试不使用变量,则代码可以工作:
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'John')")
因此,我无法输入变量(first_name),而变量“user_id”可以轻松输入。
什么可以解决问题?
I am encountering a problem while updating a table.
The code is from telegram bot. We are receiving messages from user, and asking him for a name. This is the variable 'first_name'. We already know his user_id which is integer.
Then I am trying to do
def bd_set(body):
cursor.execute(body)
connect.commit()
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},{first_name})")
and getting an error:no such column "John".
But if I try without variable, the code works:
bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'John')")
So, I cannot input varibale (first_name), while variable'user_id' inputs easily.
what can solve the issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题中的代码和两个现有答案中的代码都存在相同的主要问题:它们对一个名为 SQL 注入。
不要通过将字符串粘在一起来构建 SQL 查询。
相反,将参数单独传递给
cursor.execute()
:我用
%s
替换了此处的占位符,但根据您的数据库驱动程序,您可能必须使用 不同的语法。The code in the question and in both existing answers has the same major problem: they are wide open to a serious security vulnerability called SQL injection.
Don't build SQL queries by sticking strings together.
Instead, pass the parameters to
cursor.execute()
separately:I replaced the placeholders here with
%s
but depending on your database driver you might have to use different syntax.你的引号有问题。由于first_name是一个字符串,并且您使用的是f字符串,因此需要使用引号
您应该尝试使用准备好的语句来避免此类问题并避免sql注入
You have a problem with quotation marks. As first_name is a string, and as you are using f string, you need to use quotation marks
You should try to use prepared statements to avoid this kind of problems and to avoid sql injection