官网数据库文档

支持的数据库
https://docs.djangoproject.com/zh-hans/3.2/ref/databases/
django2.2支持MySQL5.6+的版本
MySQL驱动程序安装
我们使用Django来操作MySQL,实际上底层还是通过Python来操作的。因此我们想要用Django来操作MySQL,首先还是需要安装一个驱动程序。在Python3中,驱动程序有多种选择。比如有pymysql以及mysqlclient等。这里我们就使用mysqlclient来操作。mysqlclient安装非常简单。只需要通过pip install mysqlclient即可安装。
常见MySQL驱动介绍:
- MySQL-python:也就是MySQLdb。是对C语言操作MySQL数据库的一个简单封装。遵循了Python DB API v2
但是只支持Python2,目前还不支持Python3。 - mysqlclient:是MySQL-python的另外一个分支。支持Python3 并且修复了一些bug。
- pymysql:纯Python实现的一个驱动。因为是纯Python编写的,因此执行效率不如MySQL-python。并且也因为是纯Python编写的,因此可以和Python代码无缝衔接。
- MySQL Connector/Python:MySQL官方推出的使用纯Python连接MySQL的驱动。因为是纯Python开发的。效率不高。
创建数据库
可视化工具Navicat
配置django
settings.pyDATABASES = {'default': {# 引擎'ENGINE': 'django.db.backends.mysql',# 数据库的名字'NAME': 'django_db1',# 用户名'USER': 'root',# 密码'PASSWORD': 'root',# 地址'HOST': '127.0.0.1',# 端口号'PORT': 3306}}
初始化数据库
Pycharm工具python manage.py makemigrationspython manage.py migrate其它数据库连接方式
添加数据
原生SQL
django
依赖Django配置 ```python from django.shortcuts import render, redirect, reverse from django.http import HttpResponse from django.db import connection # mysqlclient
def index(request):
# django中的connection连接数据库# 获取游标对象cursor = connection.cursor()# 不会把查询结果直接返回cursor.execute("select * from book")print(cursor.rowcount) # 2# data = cursor.fetchone() # (1, 'Python从入门到入佛')datas = cursor.fetchall() # ((1, 'Python从入门到入佛'), (2, 'Python从入门到入灭'))print(datas)cursor.close()connection.close()return HttpResponse("首页")
<a name="dML2M"></a>#### pymysql好处是可以操作多个数据库<br />`pip install pymysql````pythonfrom django.shortcuts import render, redirect, reversefrom django.http import HttpResponsefrom pymysql import connectdef index(request):# pymysql连接数据库conn = connect(host='127.0.0.1', port=3306, database='django_db2', user='root', password='root', charset='utf8')cursor = conn.cursor()# 不会把查询结果直接返回cursor.execute("select * from book")print(cursor.rowcount) # 2# data = cursor.fetchone() # (1, 'Python从入门到入佛')datas = cursor.fetchall() # ((1, 'Python从入门到入佛'), (2, 'Python从入门到入灭'))print(datas)cursor.close()conn.close()return HttpResponse("首页")
