采用python完成用户的登录、增删改查功能

采用python完成用户的登录、增删改查功能

总体功能如下图

在这里插入图片描述
账号或密码错误,点击“登录”提示
在这里插入图片描述

登录成功后,跳转到列表页面
在这里插入图片描述
点击“编辑按钮”
在这里插入图片描述
点击“添加”按钮
在这里插入图片描述

创建项目

第一步,创建项目包
在这里插入图片描述
第二步,在项目包下创建文件夹如下图所示
分别创建4个文件夹,service 存放业务逻辑代码,static存放静态资源(如css,js文件),templates存放html页面,utils存放工具类(如连接数据库的jdbc)
在这里插入图片描述

数据库脚本如下

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `birthday` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', '123', '男', 12, '2020-2-2');
INSERT INTO `user` VALUES (3, '猪小明', '321', '男', 28, '2023-03-03');

SET FOREIGN_KEY_CHECKS = 1;

下面直接上代码

首先先下载安装对应得模块Flask和pymysql

第二,在utils中创建DBHelper模块链接数据库

import contextlib

import pymysql as mysql

class JDBC:
    @contextlib.contextmanager
    def conMysql(self):
        try:
            con = mysql.connect(host="localhost",port=3306,user="root",
                                passwd="12345678",db="pythondb",charset="utf8")
            # 获取游标
            cs = con.cursor(mysql.cursors.DictCursor)
            #返回游标
            yield cs
            con.commit()
        except Exception as e:
            print(e)
            con.rollback()
        finally:
            cs.close()
            con.close()
    # 查询方法
    def findAll(self,cursor,sql,params=None):
        cursor.execute(sql,params)
        return cursor.fetchall()
    # 添加,删除,修改
    def executeSQL(self,cursor,sql,params=None):
        return cursor.execute(sql,params)

jdbc = JDBC()
if __name__ == '__main__':
    with jdbc.conMysql() as cs:
        print(cs)

在项目包下创建一个app模块
在这里插入图片描述
这里的代码就不做过多解析了,不懂的我们可以再交流

from flask import Flask,request,redirect,render_template

# 创建APP应用
from demo1.xmtwo.utils.DBHelper import JDBC

app = Flask(__name__,template_folder="./templates")


# 创建连接数据库的对象

jdbc = JDBC()


# 登录界面
@app.route("/")
def index():
    return render_template("login.html")

# 登录
@app.route("/login",methods=["POST","GET"])
def login():
    # 根据name属性值获取账号和密码
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    with jdbc.conMysql() as cs:
        sql = "select * from user where name=%s and pwd = %s"
        row = jdbc.executeSQL(cs,sql,(username,pwd))
        if row > 0:
            return redirect("/all")
        else:
            return render_template("login.html",error_msg="账号或密码错误")
# 查询列表
@app.route("/all")
def userlist():
    with jdbc.conMysql() as cs:
        sql = "select * from user"
        result = jdbc.findAll(cs,sql)
    return render_template("main.html",users = result)

# 添加==》跳转到添加页码
@app.route("/add")
def add():
    return render_template("add.html")
# 添加==》保存数据
@app.route("/addUser",methods=["POST","GET"])
def addUser():
    # 根据表单中的name属性值获取信息
    username = request.form.get("username")
    pwd = request.form.get("pwd")
    sex = request.form.get("sex")
    age = request.form.get("age")
    birthday = request.form.get("birthday")
    with jdbc.conMysql() as cs:
        sql = "insert into user(name,sex,age,birthday,pwd) values(%s,%s,%s,%s,%s)"
        row = jdbc.executeSQL(cs,sql,(username,sex,age,birthday,pwd))
        if row > 0:
            return redirect("/all")
        else:
            return redirect("/add")

# 编辑=》根据ID查询用户跳转到编辑页面
@app.route("/edit/<userid>")
def editUser(userid):
    with jdbc.conMysql() as cs:
        sql = "select * from user where id=%s"
        result = jdbc.findAll(cs,sql,userid)
    return render_template("edit.html",user=result[0])
# 编辑=》保存数据
@app.route("/saveUser",methods=["POST","GET"])
def saveUser():
    username = request.form.get("username")
    id = request.form.get("id")
    sex = request.form.get("sex")
    age = request.form.get("age")
    birthday = request.form.get("birthday")
    with jdbc.conMysql() as cs:
        sql = "update user set name=%s,sex=%s,age=%s,birthday=%s where id=%s"
        row = jdbc.executeSQL(cs,sql,(username,sex,age,birthday,id))

    return redirect("/all")

# 删除
@app.route("/del/<userid>")
def deleteByid(userid):
    with jdbc.conMysql() as cs:
        sql = "delete from user where id = %s"
        jdbc.executeSQL(cs,sql,userid)
    return redirect("/all")

# student(stuid,stuname,stuage,stusex(单选)) 增,删,改,查

if __name__ == '__main__':
    app.run()

然后在templates创建对应的html页面
在这里插入图片描述
add.html的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加页面</title>
</head>
<body>
    <div>
        <form action="addUser" method="post">
            <table >
                <tr>
                    <td>姓名</td>
                     <td>
                         <input name="username">
                     </td>
                </tr>
                <tr>
                    <td>密码</td>
                     <td>
                         <input type="password" name="pwd">
                     </td>
                </tr>
                <tr>
                    <td>性别</td>
                     <td>
                         <input type="radio" name="sex" value="男" checked><input type="radio" name="sex" value="女" ></td>
                </tr>
                <tr>
                    <td>年龄</td>
                     <td>
                         <input name="age">
                     </td>
                </tr>
                <tr>
                    <td>生日</td>
                     <td>
                         <input type="date" name="birthday">
                     </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="添加">
                        <input type="reset" value="重置">
                    </td>
                 </tr>
            </table>
        </form>
    </div>
</body>
</html>

edit.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>修改</title>
</head>
<body>
    <div>
        <form action="/saveUser" method="post">
<!--            id隐藏域-->
            <input type="hidden" name="id" value="{{user.id}}">
            <table>
                <tr>
                    <td>姓名</td>
                    <td>
                        <input name="username" value="{{user.name}}">
                    </td>
                </tr>
                <tr>
                    <td>性别</td>
                    <td>
                        <input name="sex" value="{{user.sex}}">
                    </td>
                </tr>
                <tr>
                    <td>年龄</td>
                    <td>
                        <input name="age" value="{{user.age}}">
                    </td>
                </tr>
                <tr>
                    <td>生日</td>
                    <td>
                        <input type="date" name="birthday" value="{{user.birthday}}">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="保存">
                        <input type="reset" value="重置">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <style>
        #login{
            width: 270px;
            margin: 0 auto;
            margin-top: 15%;
        }
        .lgbt{
            text-align: center;
            padding: 15px;
        }
    </style>
</head>
<body>
    <div id="login">
        <fieldset>
            <legend>用户登录</legend>
            <form action="login" method="post">
                <table>
                    <tr>
                        <td>用户名</td>
                        <td>
                            <input name="username">
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
                        <td>
                            <input type="password" name="pwd">
                        </td>

                    </tr>
                    {% if error_msg != "" %}
                            <tr>
                                <td colspan="2" style="color:red;text-align: center;">
                                    {{error_msg}}
                                </td>
                            </tr>
                        {% endif %}
                    <tr>
                        <td colspan="2" class="lgbt">
                            <input type="submit" value="登录">
                            <input type="reset" value="重置">
                        </td>
                    </tr>
                </table>
            </form>
        </fieldset>
    </div>
</body>
</html>

main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

  <div>
      <a href="add"><button>添加</button></a>
    <table border="1" width="500px">
      <tr>
          <td>编号</td>
          <td>姓名</td>
          <td>年龄</td>
          <td>性别</td>
          <td>生日</td>
          <td>操作</td>
      </tr>
        {% for user in users %}
        <tr>
          <td>{{user.id}}</td>
          <td>{{user.name}}</td>
          <td>{{user.age}}</td>
          <td>{{user.sex}}</td>
          <td>{{user.birthday}}</td>
          <td>
              <a href="del/{{user.id}}"><button>删除</button></a>
              <a href="edit/{{user.id}}"><button>编辑</button></a>
          </td>
        </tr>
        {% endfor %}
    </table>
  </div>
</body>
</html>
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,让我来为你解答这个问题。 首先,我们需要选择一个合适的数据库来存储数据。常用的数据库有MySQL、Oracle、SQL Server等等,选择哪一个可以根据实际情况进行考虑。这里我们以MySQL为例,因为它是一个免费且广泛使用的数据库。 接下来,我们需要安装Python的MySQL驱动程序。可以使用pip命令来安装: ``` pip install mysql-connector-python ``` 安装完成后,我们可以开始编写代码实现学校教材管理系统的各项功能: 1. 连接数据库 ```python import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" ) mycursor = mydb.cursor() ``` 2. 增加数据 ```python def insert_book(title, author, price): sql = "INSERT INTO books (title, author, price) VALUES (%s, %s, %s)" val = (title, author, price) mycursor.execute(sql, val) mydb.commit() print("书籍已添加") ``` 3. 删除数据 ```python def delete_book(title): sql = "DELETE FROM books WHERE title = %s" val = (title,) mycursor.execute(sql, val) mydb.commit() print("书籍已删除") ``` 4. 修改数据 ```python def update_book(title, price): sql = "UPDATE books SET price = %s WHERE title = %s" val = (price, title) mycursor.execute(sql, val) mydb.commit() print("书籍已修改") ``` 5. 查询数据 ```python def select_book(title): sql = "SELECT * FROM books WHERE title = %s" val = (title,) mycursor.execute(sql, val) result = mycursor.fetchone() if result: print(result) else: print("未找到该书籍") ``` 6. 排序 ```python def sort_books(): sql = "SELECT * FROM books ORDER BY price ASC" mycursor.execute(sql) results = mycursor.fetchall() for result in results: print(result) ``` 7. 统计 ```python def count_books(): sql = "SELECT COUNT(*) FROM books" mycursor.execute(sql) result = mycursor.fetchone() print("总共有%d本书籍" % result[0]) ``` 8. 交互式界面设计 ```python while True: print("请选择要执行的操作:") print("1. 增加书籍") print("2. 删除书籍") print("3. 修改书籍") print("4. 查询书籍") print("5. 排序书籍") print("6. 统计书籍") print("0. 退出程序") choice = input() if choice == "1": title = input("请输入书籍名称:") author = input("请输入作者名称:") price = input("请输入书籍价格:") insert_book(title, author, price) elif choice == "2": title = input("请输入要删除的书籍名称:") delete_book(title) elif choice == "3": title = input("请输入要修改的书籍名称:") price = input("请输入修改后的价格:") update_book(title, price) elif choice == "4": title = input("请输入要查询的书籍名称:") select_book(title) elif choice == "5": sort_books() elif choice == "6": count_books() elif choice == "0": break else: print("无效的选择,请重新输入") ``` 以上代码可以实现一个简单的学校教材管理系统,包括增删查改、排序和统计功能,并且提供了交互式界面,方便用户进行操作。当然,这只是一个示例,实际应用中可能需要更多的功能和更复杂的逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java庞

你的鼓励就是我们最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值