Django cursor()增删改查和shell环境执行脚本

在Django中,cursor()方法是DatabaseWrapper对象(由django.db.connectio提供)的一个方法,用于创建一个游标对象。这个游标对象可以用来执行SQL命令,从而实现对数据库的增删改查操作。

查询(Select)

使用cursor.execute()方法执行SQL查询语句,可以获取数据库中的数据。查询your_table表中的所有记录。执行查询后,你可以使用cursor.fetchall()或cursor.fetchone()等方法来获取查询结果。

复制代码
cursor.execute("SELECT * FROM your_table")

插入(Insert)

使用cursor.execute()方法执行SQL插入语句,可以向数据库中添加新的记录。插入一条新记录。这里%s是占位符,execute()方法的第二个参数是一个列表,包含了要插入的值。

复制代码
cursor.execute("INSERT INTO your_table (column1, column2) VALUES (%s, %s)", [value1, value2])

更新(Update)

使用cursor.execute()方法执行SQL更新语句,可以修改数据库中已存在的记录。例如,你可以使用来更新your_table表中id为某值的记录的column1字段。

复制代码
cursor.execute("UPDATE your_table SET column1 = %s WHERE id = %s", [new_value, id])

删除(Delete)

使用cursor.execute()方法执行SQL删除语句,可以删除数据库中的记录。删除your_table表中id为某值的记录。

复制代码
cursor.execute("DELETE FROM your_table WHERE id = %s", [id])

示例

1,添加模型

Test/app11/models.py

复制代码
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField('date published')




class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    publication_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return self.title

2,shell 环境执行脚本

复制代码
python manage.py shell

2.1 查询数据

fetchone() 方法 查询单行数据

复制代码
# fetchall() 方法 查询单行数据
from django.db import connection

# 使用cursor执行SQL查询
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM app11_post WHERE id = (%s)",['2'])
    row = cursor.fetchone()

if row:
    print(f"Post with id 2: {row}")
else:
    print("No post found with id 2")

fetchall() 方法 查询所有数据

复制代码
# fetchall() 方法 查询所有数据
from django.db import connection
from datetime import datetime

# 使用cursor执行SQL查询获取所有Post
with connection.cursor() as cursor:
    cursor.execute("SELECT id, title, content, pub_date FROM app11_post")
    rows = cursor.fetchall()
    for row in rows:
        print(row)

print('\n')
# 使用cursor执行SQL查询获取所有Book
with connection.cursor() as cursor:
    cursor.execute("SELECT id, title, author, publication_date, price FROM app11_book")
    rows = cursor.fetchall()
    for row in rows:
        print(row)

2.2 插入数据

复制代码
from django.db import connection
from datetime import datetime
import pytz

# 使用cursor执行SQL查询插入数据
with connection.cursor() as cursor:
    # 如果你的Django项目启用了时区支持,确保你的datetime对象是带有时区信息的
    pub_date = datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC)
    
    # 对于Post模型
    cursor.execute(
        "INSERT INTO app11_post (title, content, pub_date) VALUES (%s, %s, %s)",
        ['My First Post1321', 'This is the content of my first post.', pub_date]
    )
    
    # 对于Book模型
    cursor.execute(
        "INSERT INTO app11_book (title, author, publication_date, price) VALUES (%s, %s, %s, %s)",
        ['My First Book1321', 'John Doe', '2023-01-01', 19.99]
    )

也可以用save()方法

复制代码
# 插入数据
from datetime import datetime
import pytz
from app11.models import Post

# 创建一个Post对象
post = Post(title='My First Post123', content='This is the content of my first post.123', 
            pub_date=datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC))
# 保存到数据库
post.save()



# 插入数据
from datetime import datetime
import pytz
from app11.models import Book

# 创建一个Book对象
book = Book(title='My First Book123', author='John Doe123', publication_date=datetime(2023, 1, 1, 12, 0, 0, tzinfo=pytz.UTC), price=19.99)

# 保存到数据库
book.save()

2.3 更新数据

复制代码
# 更新数据
from django.db import connection

# 新的title和content值
new_title = 'Updated Title123'
new_content = 'Updated Content123'

# 使用cursor执行SQL查询更新数据
with connection.cursor() as cursor:
    cursor.execute(
        "UPDATE app11_post SET title=%s, content=%s WHERE id=5",
        [new_title, new_content]
    )


from django.db import connection

# 新的title和price值
new_title = 'Updated Book Title123'
new_price = 29.99

# 使用cursor执行SQL查询更新数据
with connection.cursor() as cursor:
    cursor.execute(
        "UPDATE app11_book SET title=%s, price=%s WHERE id=5",
        [new_title, new_price]
    )

2.4 删除数据

复制代码
from django.db import connection

# 要删除的记录的id
post_id = 5

# 使用cursor执行SQL查询删除数据
with connection.cursor() as cursor:
    cursor.execute(
        "DELETE FROM app11_post WHERE id = %s",
        [post_id]
    )

    
from django.db import connection

# 要删除的记录的id
book_id = 5

# 使用cursor执行SQL查询删除数据
with connection.cursor() as cursor:
    cursor.execute(
        "DELETE FROM app11_book WHERE id = %s",
        [book_id]
    )
相关推荐
TDengine (老段)2 小时前
TDengine 时间函数 WEEKDAY() 用户手册
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
TDengine (老段)2 小时前
从 ETL 到 Agentic AI:工业数据管理变革与 TDengine IDMP 的治理之道
数据库·数据仓库·人工智能·物联网·时序数据库·etl·tdengine
LQ深蹲不写BUG4 小时前
MySql的事务机制
数据库·mysql
逼子格5 小时前
【Proteus仿真】定时器控制系列仿真——秒表计数/数码管显示时间
数据库·单片机·嵌入式硬件·51单片机·proteus·定时器·硬件工程师
stein_java6 小时前
Mybatis-7 XML映射器
数据库·sql·mybatis
xhbh6666 小时前
开发效率翻倍:资深DBA都在用的MySQL客户端利器
数据库·mysql·数据库连接工具·mysql 连接工具
LJC_Superman6 小时前
Web与Nginx网站服务
运维·服务器·前端·网络·数据库·nginx·vim
java水泥工7 小时前
校园管理系统|基于SpringBoot和Vue的校园管理系统(源码+数据库+文档)
数据库·vue.js·spring boot
高山有多高7 小时前
详解文件操作
c语言·开发语言·数据库·c++·算法