42.通过原生SQL语句进行操纵mysql数据库
2024-08-31 20:46:44
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的终端运行窗口也打印出了数据信息
最新文章
- Media Player插件
- Linux搭建python环境中cx_Oracle模块安装遇到的问题与解决方法
- 1028 C语言文法
- RCC 2014 Warmup (Div. 2)
- My97DatePicker 没有权限问题
- java-mina(nio 框架)
- 322. Coin Change
- github 提交报403 forbidden的错误解决
- EDM(邮件营销)
- JS延时一秒执行
- Spring security csrf实现前端纯html+ajax
- android开发_Eclipse新建项目+新建模拟器
- C#中五种访问修饰符作用范围 public、private、protected、internal、protected internal
- Android开发技术周报183学习记录
- MATLAB:图像水平、垂直、水平垂直镜像、转置、旋转变换(flipdim、mirror、transp、imrotate函数)
- UVa 10054 The Necklace(无向图欧拉回路)
- 常见笔记本进入bios方法
- 怎么申请 bing api key
- BZOJ3544 [ONTAK2010]Creative Accounting
- iOS性能调优系列(全)