15.2.5 基于数据库的签到系统

更新于 2026年10月13日 版权声明
15.2.5 基于数据库的签到系统

图示

①在MySQL中建立一个数据库和一个表,如图15-7所示。

图示

图15-7 MySQL中建立一个数据库

②建立通用的dbHelper.py。

import pymysql
class dbHelper():
    def __init__(self,host,user,password,dbName):
        self.host = host
        self.user = user
        self.password = password
        self.dbName = dbName
    # 建立连接
    def connect(self):
        # 打开数据库连接
        self.db = pymysql.connect(self.host,self.user,self.password,self.dbName)
        # 使用cursor()方法获取操作游标
        self.cursor = self.db.cursor()
    # 关闭连接
    def close(self):
        # 关闭cursor
        self.cursor.close()
        # 关闭连接
        self.db.close()
    # 查询所有:传一个SQL语句
    def get_all(self, sql):
        res = ()
        try:
            # 得到连接
            self.connect()
            # 执行传入的SQL语句
            self.cursor.execute(sql)
            #查询所有
            res = self.cursor.fetchall()
            self.close()
        except:
            print('查询失败')
        return res
    def insert(self,sql):
        count =0
        try:
            # 得到连接
            self.connect()
            # 执行传入的SQL语句
            count = self.cursor.execute(sql)
            #提交事务
            self.db.commit()
            self.close()
        except:
            print('事务提交失败')
            # 回滚
            self.db.rollback()
        return count(https://www.daowen.com)

③在SignPageHandler中完善SQL语句。

class SignPageHandler(web.RequestHandler):    '''签到界面'''    def get(self):        self.render("login.html")    # 使用post 接收数据    def post(self):        name = self.get_argument('name')        xh = self.get_argument('xh')        dd = self.get_argument('dd')        date  =datetime.now().strftime('%Y-%m-%d %H:%M:%S')        # 保存到数据库        from dbHelper import dbHelper        # 建立连接        dbconn = dbHelper('localhost', 'root', '123456', 'sign')        # SQL语句:        sql = "insert into sign (name, xh, dd, time) VALUES ('{0}', '{1}','{2}', '{3}')".format(name,xh,dd,date)        count = dbconn.insert(sql)        if count > 0:        self.write('签到成功')

✍AI写作