42.通过原生SQL语句进行操纵mysql数据库

views.py文件中:
from django.shortcuts import render
# 导入connection模块
from django.db import connection


def index(request):
# 使用connection模块中的函数cursor(),进行获取当前的游标,只有获取了游标,python才能够找到在settings.py中的数据库信息,进行数据库的连接。
    cursor = connection.cursor()语句,都要包含在execute()函数中执行。
    # 想要执行任何的sql
    cursor.execute("insert into db01(id,name,author) values(null,'三国演义','罗贯中')")
    return render(request,'index.html')
在settings.py中配置连接数据库的信息:
DATABASES = {
    'default': {
        # 指定所使用的的数据库引擎
        'ENGINE': 'django.db.backends.mysql',
        # 指定所使用的数据库的名字
        'NAME': 'db01',
        # 指定所使用的的用户名
        'USERNAME':'root',
        # 指定所使用的的密码
        'PASSWORD':'root',
        # 指定mysql数据库的主机连接地址
        'HOST':'127.0.0.1',
        # 指定mysql数据库的端口号
        'PORT':'3306'
    }
}
运行项目。查看数据库表db01中数据是否已经插入了。

在这里插入图片描述

查询数据表中的数据信息。
from django.shortcuts import render
from django.db import connection


def index(request):
    cursor = connection.cursor()
    cursor.execute("select * from  db01")
    # 从数据库表db01中选择所有的数据信息
    # 将返回的结果返回给books.
    books = cursor.fetchall()
    # 使用for循环遍历每一行数据信息,并且进行打印。
    for book in books:
        print(book)
# 同时也可以在浏览器中进行显示
	context = {
	        'book':book
	    }
    return render(request,'index.html',context=context)
此时,如果要在浏览器中进行显示的话,就要在index.htmlDTL模板中进行接收。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ book }}
</body>
</html>
此时显示的信息,是以元组的形式进行显示的。

在这里插入图片描述

同时,在pycharm的终端运行窗口也打印出了数据信息

在这里插入图片描述

发布了75 篇原创文章 · 获赞 2 · 访问量 2736

猜你喜欢

转载自blog.csdn.net/zjy123078_zjy/article/details/104032750
今日推荐