Django 执行原生SQL
在Django中执行原生SQL语句,可以使用Django提供的Django.db.connection
模块。以下是一些示例:
- 执行一个查询并获取结果:
from django.db import connection
def custom_sql():
# 执行查询
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM my_table WHERE id = %s", [1])
rows = cursor.fetchall()
return rows
- 执行一个更新操作:
from django.db import connection
def custom_sql_update():
with connection.cursor() as cursor:
cursor.execute("UPDATE my_table SET status = %s WHERE id = %s", ['inactive', 1])
connection.commit() # 更新操作需要提交事务
- 执行一个删除操作:
from django.db import connection
def custom_sql_delete():
with connection.cursor() as cursor:
cursor.execute("DELETE FROM my_table WHERE id = %s", [1])
connection.commit() # 删除操作需要提交事务
- 执行一个创建表的操作:
from django.db import connection
def custom_sql_create_table():
with connection.cursor() as cursor:
cursor.execute("CREATE TABLE my_new_table (id INT PRIMARY KEY, name VARCHAR(100))")
- 执行多个SQL语句:
from django.db import connection
def custom_sql_multiple_statements():
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM my_table WHERE id = %s; SELECT * FROM other_table WHERE status = %s", [1, 'active'])
rows = cursor.fetchall()
return rows
注意:在使用原生SQL时,请务必小心防范SQL注入攻击。始终使用参数化查询(例如,使用%s
和列表/元组传递参数),而不是拼接字符串。
评论已关闭