教你用python实现一个*面的小型图书管理系统

时间:2022-12-01 23:25:24

一、需求了解

功能模块

教你用python实现一个*面的小型图书管理系统

图书信息

教你用python实现一个*面的小型图书管理系统

二、环境准备

安装mysql数据库

参考文章:

MySQL数据库压缩版本安装与配置

MySQL msi版本下载安装图文教程

创建数据库表

  • 创建数据库

CREATE DATABASE bookmanage;

  • 使用数据库

use bookmanage;

  • 创建表

create table books(
id int unsigned primary key auto_increment not null,
name varchar(20) default “”,
position varchar(40) default “”,
status enum(‘在库', ‘出借') default ‘在库',
borrower varchar(20) default “”
);

  • 插入数据

insert into books(name, position) value (‘python从入门到放弃', ‘A-1-1');

  • 查询数据

select * from books where id=2;

  • 修改数据

update books set name=‘python';

  • 删除数据

delete from book where id=3;

三、代码实现

引入pymysql模块

  • 安装pymysql

命令:pip install pymysql

  • 封装操作数据库模块
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -*- coding: utf-8 -*-
"""
===============================
@Time    : 2021/5/18 15:56
@Author  : flora.chen
@FileName: handle_mysql.py
@Software: PyCharm
===============================
"""
import pymysql
 
class MysqlDB:
    """
    操作mysql数据库
    """
    def __init__(self, host, user, pwd, database=None, port=3306):
        """
        初始化数据库链接
        :param host: 主机地址
        :param user: 用户名
        :param pwd: 密码
        :param database: 数据库名称,默认为空
        :param port: 端口号,默认3306
        """
        self.conn = pymysql.connect(
            host=host,
            user=user,
            password=pwd,
            database=database,
            port=port,
            cursorclass=pymysql.cursors.DictCursor
        )
        # 创建一个游标对象
        self.cur = self.conn.cursor()
 
    def update(self, sql):
        """
        进行增删改操作
        :param sql: 需要执行的SQL
        :return:
        """
        # 执行SQL
        result = self.cur.execute(sql)
        # 提交事务
        self.conn.commit()
        return result
 
    def query(self, sql, one=False):
        """
        进行查询操作
        :param one: 判断是要返回所有查询数据还是第一条,默认是所有
        :param sql: 要执行的SQL
        :return:
        """
        # 执行SQL
        self.cur.execute(sql)
        if one:
            return self.cur.fetchone()
        else:
            return self.cur.fetchall()
 
    def close(self):
        """
        断开游标,关闭数据库连接
        :return:
        """
        self.cur.close()
        self.conn.close()
 
 
if __name__ == "__main__":
    db = MysqlDB(host="localhost", user="root", pwd="root")
    print(db.query("select * from bookmanage.books"))
    # db.update("insert into bookmanage.books(name, position) value ('python从入门到放弃', 'A-1-1');")

图案管理系统后台实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# -*- coding: utf-8 -*-
"""
===============================
@Time    : 2021/5/18 16:39
@Author  : flora.chen
@FileName: bookmanager.py
@Software: PyCharm
===============================
"""
from handle_mysql import MysqlDB
 
db = MysqlDB(host="localhost", database="bookmanage", user="root", pwd="root")
 
 
class BookManage:
    """
    图书管理系统
    """
 
    @staticmethod
    def print_menu():
        """
        菜单打印
        :return:
        """
        print("---------------------菜单-------------------------")
        print("[1]: 添加图书")
        print("[2]: 修改图书")
        print("[3]: 删除图书")
        print("[4]: 查询图书")
        print("[5]: 图书列表")
        print("[6]: 出借图书")
        print("[7]: 归还图书")
        print("[8]: 退出")
 
    def add_book(self):
        """
        [1]: 添加图书
        :return:
        """
        print("****************添加图书****************")
        name = input("请输入书名:")
        position = input("请输入图书位置:")
        if name and position:
            db.update("insert into books(name, position) value ('{}', '{}');".format(name, position))
            print("图书添加成功")
        else:
            print("书名或者图书位置不能为空,请重新输入!")
 
        num = input("继续添加请输入1, 回车退回主菜单")
        if num == "1":
            self.add_book()
 
    def update_book(self):
        """
        [2]: 修改图书
        :return:
        """
        print("****************修改图书****************")
        book_id = input("请输入需要修改的图书ID:")
        result = db.query("select * from books where id={};".format(book_id), one=True)
        if result:
            print("当前数据为:{}".format(result))
            name = input("重新输入书名,不修改输入回车:") or result["name"]
            position = input("重新输入位置,不修改输入回车:") or result["position"]
            db.update("update books set name='{}', position='{}' where id={};".format(name, position, book_id))
            print("修改成功")
        else:
            print("您输入的图书ID不存在,请重新输入~")
 
        num = input("继续修改请输入1, 回车退回主菜单")
        if num == "1":
            self.update_book()
 
    def delete_book(self):
        """
        [3]: 删除图书
        :return:
        """
        print("****************删除图书****************")
        book_id = input("请输入需要修改的图书ID:")
        result = db.query("select * from books where id={};".format(book_id), one=True)
        if result:
            print("当前数据为:{}".format(result))
            confirm_num = input("确定需要删除这本书吗?确认请按1,取消请按2:")
            if confirm_num == "1":
                db.update("delete from books where id={};".format(book_id))
                print("删除成功")
            else:
                print("已确认不删除该书籍~")
        else:
            print("系统中未找到该书籍!")
 
        num = input("继续删除请输入1, 回车退回主菜单")
        if num == "1":
            self.delete_book()
 
    def query_book(self):
        """
        [4]: 查询图书
        :return:
        """
        print("****************查询图书****************")
        name = input("请输入您要查询的图书名称(模糊匹配):")
        if name:
            result = db.query("select * from books where name like '%{}%';".format(name))
            if result:
                print("当前查询到如下书籍信息:{}".format(result))
            else:
                print("未查询到相关书籍信息~")
        else:
            print("书名不能为空!")
 
        num = input("继续查询请输入1, 回车退回主菜单")
        if num == "1":
            self.query_book()
 
    def book_list(self):
        """
        [5]: 图书列表
        :return:
        """
        print("****************图书列表****************")
        result = db.query("select * from books;")
        for i in result:
            print("编号:{}, 书籍名:{}, 位置:{}, 状态:{}, 借阅人:{}".format(i["id"], i["name"], i["position"], i["status"],
                                                               i["borrower"]))
 
    def borrow_book(self):
        """
        [6]: 出借图书
        :return:
        """
        print("****************出借图书****************")
        book_id = input("请输入需要借阅的图书ID:")
        result = db.query("select * from books where id={};".format(book_id), one=True)
        if result:
            if result["status"] == "出借":
                print("抱歉,该书已经借出!")
            else:
                while True:
                    borrower = input("请输入借阅者的名字:")
                    if borrower:
                        db.update("update books set borrower='{}' where id={};".format(borrower, book_id))
                        db.update("update books set status='出借' where id={};".format(book_id))
                        print("图书借阅成功~")
                        break
                    else:
                        print("借阅者的名字不能为空, 请重新输入")
        else:
            print("未查询到相关书籍信息~")
 
        num = input("继续借阅请输入1, 回车退回主菜单")
        if num == "1":
            self.borrow_book()
 
    def back_book(self):
        """
        [7]: 归还图书
        :return:
        """
        print("****************归还图书****************")
        book_id = input("请输入需要归还的图书ID:")
        result = db.query("select * from books where id={};".format(book_id), one=True)
        if result:
            if result["status"] == "在库":
                print("该书是在库状态,请确认图书编号是否正确!")
            else:
                db.update("update books set status='在库' where id={};".format(book_id))
                db.update("update books set borrower='' where id={};".format(book_id))
                print("书籍归还成功~")
        else:
            print("未查询到相关书籍信息~")
 
        num = input("继续归还书籍请输入1, 回车退回主菜单")
        if num == "1":
            self.borrow_book()
 
    def quit(self):
        """
        [8]: 退出
        :return:
        """
        print("****************退出****************")
        db.close()
 
    def main(self):
        """
        程序运行的流程控制
        :return:
        """
        print("---------------欢迎进入图书管理系统----------------")
        while True:
            self.print_menu()
            num = input("请输入选项:")
            if num == "1":
                self.add_book()
            elif num == "2":
                self.update_book()
            elif num == "3":
                self.delete_book()
            elif num == "4":
                self.query_book()
            elif num == "5":
                self.book_list()
            elif num == "6":
                self.borrow_book()
            elif num == "7":
                self.back_book()
            elif num == "8":
                self.quit()
                break
            else:
                print("您的输入有误~ 请按照菜单提示输入,谢谢!")
 
 
if __name__ == "__main__":
    book = BookManage()
    book.main()

到此这篇关于教你用python实现一个*面的小型图书管理系统的文章就介绍到这了,更多相关Python实现图书管理系统内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/FloraCHY/article/details/117002398