gpt4 book ai didi

python - 如何在 Django Python 中的原始 SQL 中插入参数

转载 作者:太空狗 更新时间:2023-10-29 20:40:59 25 4
gpt4 key购买 nike

我有这个代码

myquery =   '''SELECT * from users 
where id = 10 and
city = 20 and
state = 30'''

我想用三个变量替换那些

var_id = bla
var_city = bla
var_state = bla

最佳答案

使用 params argument to raw() :

var_id = 10
var_city = 20
var_state = 30

mymodel.objects.raw('''SELECT * from users
where id = %s and
city = %s and
state = %s ''', [var_id, var_city, var_state])

params 是参数列表。您将在查询字符串中使用 %s 占位符(无论您的数据库引擎如何);它们将被 params 列表中的参数替换。


来自 Django 文档的重要说明:

Warning Do not use string formatting on raw queries!

It's tempting to write the above query as:

>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)

Don't.

Using the params list completely protects you from SQL injection attacks, a common exploit where attackers inject arbitrary SQL into your database. If you use string interpolation, sooner or later you'll fall victim to SQL injection. As long as you remember to always use the params list you'll be protected.

关于python - 如何在 Django Python 中的原始 SQL 中插入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13189563/

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