views.py文件中:
from django.shortcuts import render
from django.db import connection
def index(request):
cursor = connection.cursor()语句,都要包含在execute()函数中执行。
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',
'HOST':'127.0.0.1',
'PORT':'3306'
}
}
运行项目。查看数据库表db01中数据是否已经插入了。
查询数据表中的数据信息。
from django.shortcuts import render
from django.db import connection
def index(request):
cursor = connection.cursor()
cursor.execute("select * from db01")
books = cursor.fetchall()
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的终端运行窗口也打印出了数据信息