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的终端运行窗口也打印出了数据信息

最新文章

  1. Media Player插件
  2. Linux搭建python环境中cx_Oracle模块安装遇到的问题与解决方法
  3. 1028 C语言文法
  4. RCC 2014 Warmup (Div. 2)
  5. My97DatePicker 没有权限问题
  6. java-mina(nio 框架)
  7. 322. Coin Change
  8. github 提交报403 forbidden的错误解决
  9. EDM(邮件营销)
  10. JS延时一秒执行
  11. Spring security csrf实现前端纯html+ajax
  12. android开发_Eclipse新建项目+新建模拟器
  13. C#中五种访问修饰符作用范围 public、private、protected、internal、protected internal
  14. Android开发技术周报183学习记录
  15. MATLAB:图像水平、垂直、水平垂直镜像、转置、旋转变换(flipdim、mirror、transp、imrotate函数)
  16. UVa 10054 The Necklace(无向图欧拉回路)
  17. 常见笔记本进入bios方法
  18. 怎么申请 bing api key
  19. BZOJ3544 [ONTAK2010]Creative Accounting
  20. iOS性能调优系列(全)

热门文章

  1. webdriver的常用方法
  2. remote: error: hook declined to update refs/heads
  3. 目标检测之RCNN,fast RCNN,faster RCNN
  4. HDU_2084_DP
  5. thinkphp远程执行漏洞的本地复现
  6. linux下使用gdb对php源码调试
  7. 什么?接口中方法可以不是抽象的「JDK8接口新语法的深度思考」
  8. prometheus operator(Kubernetes 集群监控)
  9. btrfs文件系统简单学习
  10. light oj 1014 - Ifter Party分解因子