# 获取数据库连接,并返回一个cursor的游标
def conn_db():
global conn
conn=pymysql.connect(host='localhost',user='root',
passwd='813916ZSY',db='student',port=3306,
charset='utf8')
cursor=conn.cursor()
return cursor
第一行 :定义了一个函数conn_db,无参数
第二行:利用pymysql.Connection库中的cursor()方法获取一个游标
第三行:定义一个全局参数conn,conn是一个pymysql.Connection对象,表示与数据库的 连接(全局定义可以使得该参数的值在函数外部也可以修改)
第四行:通过pymysql.connect()的方法连接数据库,host为数据库服务器的地址(localhost表示本机),user表示数据库的用户名,password为数据库的连接密码,db为数据库的名字,port为数据路的端口号,charset为数据库的编码类型
#渲染学籍管理界面
def studentManagement(request):
username = request.session['username']
cursor = conn_db()
sql = "select * from student"
cursor.execute(sql)
row_list = cursor.fetchall()
cursor.close()
return render(request, 'studentManagement.html',{"username":username, "row_list" : row_list})
第一行:定义一个studentManagement的代码,参数为request(是Django的HttpRequest对象)
第二行:从session对话中获取用户名username
第三行:调用conn_db()函数,连接数据库
第四行:写一个sql语句,表示查询student表中的所有内容,其中*号表示表头的所有内容,可以替换成表头的所有内容(例如:此处的*号可以换成sno,sname,password,ssage,ssex,politics,phone,homeph,adress,cet,compgrade)
第五行:执行sql语句,cursor是游标(是一个对象)
第六行:将查找的所有内容放入row_list中,row_list是列表(每一行为一个元组)
第七行:关闭游标
第八行:渲染模板
注:
render()函数:render(request, template_name, context=None, content_type=None, status=None, using=None)
-
request:当前的HTTP请求对象,包含了用户请求的所有信息(如请求方法、请求参数、用户会话等)。 -
template_name:模板文件的路径,相对于TEMPLATES配置中的DIRS目录。 -
context:一个字典,包含传递给模板的上下文数据(例如:{"username": username, "row_list": row_list})。键是模板中使用的变量名,值是对应的Python对象。(模板文件指的是要渲染的HTML模板) -
content_type:响应的内容类型,默认为text/html。 -
status:HTTP状态码,默认为200(表示成功)。 -
using:指定使用的模板引擎,默认使用settings中配置的模板引擎。
2万+

被折叠的 条评论
为什么被折叠?



