Greenery
2023-07-29
来自新加坡
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(req): import pymysql.cursors # 连接数据库 connection = pymysql.connect(host='localhost', user='root', password='root', database='db', cursorclass=pymysql.cursors.DictCursor) with connection: with connection.cursor() as cursor: # 读取纪录 sql = "SELECT `date`, `city`,`temp` FROM `weather1`" cursor.execute(sql) result = cursor.fetchall() print(result) # 将ctx转换为一个字典,以便传递给模板 ctx = {'weathers': result} return render(req, 'weather.html', ctx) # weather.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Zhe jiang Weathers</title> </head> <body> <ul> {% for w in weathers %} <li> {{w.city}} | {{w.date}} | {{w.temp}} </li> {% endfor %} </ul> </body> </html>
展开
Cy23
2023-02-01
来自辽宁
from django.shortcuts import render import pymysql import time def index(request): conn = pymysql.connect( host='localhost', user='root', password='', database='pydb', cursorclass=pymysql.cursors.DictCursor) with conn: with conn.cursor() as cursor: sql = "select * from `weather` where city =%s" cursor.execute(sql, ('沈阳')) result = cursor.fetchall() context = {} context['city'] = result[0]["city"] context['date'] = time.strftime("%Y-%m-%d", time.strptime(result[0]["date"], "%Y%m%d")) context['temp'] = result[0]["temp"] return render(request, 'index.html', context)
展开