[Django-05 ]自定义sql查询

自定义sql查询

settings.py 设置数据库

java 复制代码
DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',  # 数据库引擎
        'NAME': 'study',  # 数据库名字
        'USER': 'root',  # 用户名
        'PASSWORD': 'mysqlgame123',  # 密码
        'HOST': 'xxxxxx',  # HOST
        'PORT': '3306',  # 端口
        'OPTIONS': {'charset': 'utf8mb4'},  # 打开数据库 编码格式 ------解决4字节表情无法储存问题
    }
}

这样后续的操作都会在这个数据库中

自定义sql查询

这里在一些多表关联的时候是特别特别有用的,也是实际开发中不可避免的知识点

  • with 写法
java 复制代码
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM app_grade WHERE grade_name='二班'")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
  • 普通写法
java 复制代码
cursor=connection.cursor()
cursor.execute("SELECT * FROM app_grade WHERE grade_name='二班'")
rows = cursor.fetchall()
for row in rows:
    print(rows)
cursor.close()
相关推荐
—Miss. Z—7 小时前
备份与恢复
数据库·oracle
这个DBA有点耶10 小时前
Oracle 迁移金仓兼容性评估指南:5 大维度深度拆解
数据库·oracle·架构
Suhan4213 小时前
SQLAlchemy的两种查询query()查询、stmt=select()查询
数据库·python·sql·oracle
瀚高PG实验室13 小时前
SQL优化案例:使用分区表优化SQL查询性能
linux·服务器·数据库·sql·microsoft·postgresql
今天AI了吗14 小时前
从聊天到委派:AI Agent 如何推进长期任务
数据库·人工智能·python·sql·rust
—Miss. Z—15 小时前
第11章 故障管理
网络·数据库·oracle
名字还没想好☜17 小时前
Go 的 database/sql 连接池实战:SetMaxOpenConns 怎么配、连接泄漏怎么查
数据库·sql·golang·go·数据库连接池
大眼、不聚光17 小时前
2.oracle--表空间管理
数据库·oracle
Csvn18 小时前
📊 SQL 入门 Day 20:锁机制
后端·sql