MySQL 用变量更新

发布于 2025-01-10 10:37:02 字数 514 浏览 2 评论 0原文

我在更新表时遇到问题。 该代码来自电报机器人。我们正在收到用户的消息,并询问他的姓名。这是变量“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

永不分离 2025-01-17 10:37:02

问题中的代码和两个现有答案中的代码都存在相同的主要问题:它们对一个名为 SQL 注入

不要通过将字符串粘在一起来构建 SQL 查询。

相反,将参数单独传递给 cursor.execute()

def bd_set(body, parameters=None):
    cursor.execute(body, parameters)
    connect.commit()

bd_set(
    f"INSERT INTO user_info (user_id, first_name) VALUES(%s, %s)",
    (user_id, first_name),
)

我用 %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:

def bd_set(body, parameters=None):
    cursor.execute(body, parameters)
    connect.commit()

bd_set(
    f"INSERT INTO user_info (user_id, first_name) VALUES(%s, %s)",
    (user_id, first_name),
)

I replaced the placeholders here with %s but depending on your database driver you might have to use different syntax.

睡美人的小仙女 2025-01-17 10:37:02

你的引号有问题。由于first_name是一个字符串,并且您使用的是f字符串,因此需要使用引号

bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'{first_name}')")

您应该尝试使用准备好的语句来避免此类问题并避免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

bd_set(f"INSERT INTO user_info (user_id,first_name) VALUES({user_id},'{first_name}')")

You should try to use prepared statements to avoid this kind of problems and to avoid sql injection

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文