Bookstore Management System Course Design (sql server+python)

I. Overview

According to the course requirements, I need to complete a database course design. Combined with the reality, I chose a relatively familiar bookstore as my design object. According to the online search and inquiry, I learned some of the daily work of the bookstore and the content and type of data, so I conducted a demand analysis and formulated ER model to analyze the design style and requirements of the database.

2. Demand analysis

According to the needs of the bookstore, the daily life of the bookstore is mainly divided into four situations:

  1. Purchase: Each book has book information such as book type, book price, book publisher, book version, etc. Only after screening the books and sorting out the book information can purchases be made.
  2. Storage: After the books are purchased, it is necessary to determine whether the books are already in the library. If there is no such book information, it is necessary to store the basic information of the books in the library and add the number of books in the library; if there are the same For book information, there is no need to enter book information, but directly update the existing quantity of books.
  3. Sales: Books that are sold must also record the information of the book, and only after confirming the information of the book can it be recorded and sold.
  4. Out of the warehouse: For the books sold out, the data should be updated in time, the existing number of books should be updated and checked, and the sales records should be recorded for reference in future purchases. If the books are sold out, this can remind the operator to purchase.

3. Conceptual Design

1. Abstract entities

According to the needs of the database, the following entities can be abstracted:

  1. book information
  2. customer information
  3. supplier information
  4. Inventory
  5. Purchase information
  6. sales information

2. Entity attribute diagram and sub-ER diagram

The following is the attribute diagram of each entity, as well as the sub-ER diagram:
Figure 1 Book information entity attribute diagram
insert image description here

Fig.2 Customer information entity attribute diagram
insert image description here
Fig.3 Supplier information entity attribute diagram
insert image description here

Figure 4 Inventory Information Entity Attribute Map
insert image description here

Figure 5 ER diagram for purchases
insert image description here
Figure 6 ER diagram for sales
insert image description here
Figure 7 Overall ER diagram
insert image description here

4. Logical structure design

The relational data schema is as follows:

  1. Book information: book number, book title, book classification, book publisher, price, number of pages
  2. Customer information: customer number, customer name, customer gender, customer age, customer phone number
  3. Supplier Information: Supplier Number, Supply Book Number, Supplier Name, Supplier Phone Number, Supply Quantity
  4. Purchase information: book number, purchaser name, supplier number, book purchase quantity, purchase date
  5. Sales information: sales order number, sales date, book title, customer information, quantity, total price
  6. Inventory information: book title, book type, number of books in stock

5. Database physical design and implementation

1. Physical structure design

According to the logical structure design, the logical data model is obtained, and the physical model of the database is formulated as follows, which introduces 6 tables, namely "purchase information", "supplier information", "inventory information", "customer information", and "sales information" , "Book Information"

Figure 8 Database physical model diagram
insert image description here

2. Table creation

Table 1 Book information table
insert image description here

create table 图书信息(
	书号 nchar(10) foreign key references 库存信息(书号),
	图书名称 nchar(20) NOT NULL ,
	图书类别 nchar(20) NOT NULL ,
	图书出版社 nchar(20) NOT NULL,
	图书价格 float not null,
	图书页数 int not null
)

Table 2 Customer Information Form
insert image description here

create table 顾客信息(
	顾客号 nchar(10) NOT NULL PRIMARY KEY,
	姓名 nchar(20) NOT NULL,
	性别 nchar(20) NOT NULL,
	年龄 int NOT NULL,
	电话号码 nchar(20) not null,
	)

Table 3 Supplier Information Form
insert image description here

create table 供应商信息(
	供应商号 nchar(10) NOT NULL PRIMARY KEY,
	供应商名称 nchar(20) NOT NULL,
	电话号码 nchar(20) NOT NULL,
	供应商地址 nchar(40) not null 
)

Table 4 purchase information table
insert image description here

create table 进货信息(
	进货单号 nchar(10) NOT NULL PRIMARY KEY,
	书号 nchar(10) not NULL,
	图书类别 nchar(20) not NULL,
	供应商号 nchar(10) foreign key references 供应商信息(供应商号),
	图书进货数量 int NOT NULL,
	进货日期 date default (getdate())
)

Table 5 Sales information table
insert image description here

create table 销售信息(
	销售单号 nchar(10) NOT NULL PRIMARY KEY,
	书号 nchar(10) foreign key references 库存信息(书号),
	顾客号 nchar(10) foreign key references 顾客信息(顾客号),
	图书销售数量 int NOT NULL,
	销售日期 date default (getdate()),
	销售金额 float null default (0)
)

Table 6 Inventory Information Table
insert image description here

create table 库存信息(
	书号 nchar(10) PRIMARY KEY, 
	图书类别 nchar(20) not null,
	图书数量 int not null
)

3. Integrity constraints

--设置完整性约束
--设置销售金额默认值是
alter table 销售信息 add default(0) for 销售金额

--设置级联删除更新,当库存信息中书号改变,图书信息中的学号也改变,当库存信息中数据删除时,图书中的数据也级联删除
alter table 图书信息 add constraint 库存删除 foreign key(书号) references 库存信息(书号) on delete CASCADE on update cascade

--设置库存信息和销售信息级联更新
alter table 销售信息 add constraint 销售更新 foreign key(书号) references 库存信息(书号) on update cascade 

--进货信息与库存信息之间级联删除更新
alter table 进货信息 add constraint 进货删除 foreign key(书号) references 库存信息(书号) on delete CASCADE on update cascade

--进货信息和供应商信息设置级联删除更新,使数据保持一致
alter table 进货信息 add constraint 供应商删除 foreign key(供应商号) references 供应商信息(供应商号) on delete CASCADE on update cascade

--销售信息与顾客信息建立级联删除,并在顾客号上,建立级联更新,以便数据更改。
alter table 销售信息 add constraint 顾客删除 foreign key(顾客号) references 顾客信息(顾客号) on delete CASCADE on update cascade

6. Database operation requirements and implementation

According to the course design requirements and combined with the database design, I made a detailed analysis of the realization of some functions. The following involves stored procedures and triggers, and uses related technologies. The required sql statements are as follows: 1. Create a stored procedure to query a
certain The purchase and sales of various books within a certain period of time;

create procedure 进售信息
	@date1 date,
	@date2 date	
	AS
	select * from 进货信息 where 进货信息.进货日期>=@date1 and 进货信息.进货日期<=@date2
	select * from 销售信息 where 销售日期>=@date1 and 销售日期<=@date2
	go

--用于exec语句传参并使用存储结构
	exec 进售信息 '2020-1-20','2020-1-23'

Execution results:
insert image description here
2. Create a view to query the total inventory of various books;

create view zl_numb 
as 
 select 图书类别,sum(图书数量) as 种类数量 from 库存信息 group by 图书类别
 go

Results of the:
insert image description here

3. Create a trigger to automatically modify the total amount of the corresponding book and the quantity of the book in the storage warehouse when the book is put into storage. When the book inventory is 0, delete the book inventory information and book information, and automatically add it to the In the inventory information;

-- 进货入库
	CREATE TRIGGER 库存增加 on 进货信息 for insert AS
	declare @num int
	declare @bnum nchar(10)
	declare @f  int
	declare @kinds nchar(20)
	select @num=图书进货数量,@bnum=书号,@kinds=图书类别 from inserted
	select @f=COUNT(@bnum)from 库存信息 where 书号=@bnum
	if @f>0
	begin
	update 库存信息 set 图书数量=图书数量+@num where 书号=@bnum
	end
	if @f<=0
	begin
		insert into 库存信息 values (@bnum,@kinds,@num)
	end
	go

--销售出库
	CREATE TRIGGER 库存减少 on 销售信息 for insert AS
		declare @num int
		declare @bnum nchar(10)
		declare @num1 int
		select @num=图书销售数量,@bnum=书号 from inserted
		select @num1=图书数量 from 库存信息 where @bnum=书号
		if @num1 <= @num
			begin
			if @num1=@num
			begin
			delete 库存信息 where 书号=@bnum
			end
			else
			begin
			print '销售失败,图书数量不够!'
			Rollback TRANSACTION
			end
			end
		else
			begin
			update 库存信息 set 图书数量=图书数量-@num where 书号=@bnum
			end
		go

Inventory information and purchase information before modification:
The picture below is the inventory information
insert image description here
The picture below is the purchase information
insert image description here
The following purchases 2 books with book number 001:

insert into 进货信息 (进货单号,书号,图书类别,供应商号,图书进货数量)values('a4','001','中国古代小说','01',2)

insert image description here

After execution, the inventory information is as follows, and the function has been successfully realized.
insert image description here
Next, test the function of selling out of the warehouse. The
sales information before sales is as follows:
insert image description here
insert a piece of sales data below, and sell 2 books of No. 001, but the books need to be put on the shelf before the sale, that is, the purchase Improve the information of the book and set the price.
The Sql statement is as follows:

insert into 图书信息 values ('001','水浒传','中国古代小说','新华出版社',45.2,540)

insert image description here

insert into 销售信息 (销售单号,书号,顾客号,图书销售数量) 
values ('b1','001','1',2)

insert image description here
Inventory results after execution:
insert image description here
Combined with the actual situation, I designed
a Sql statement for purchasing new books and directly adding them to the inventory:

insert into 进货信息 (进货单号,书号,图书类别,供应商号,图书进货数量)values('a5','005','中国散文','01',20)

Purchase information
insert image description here
Inventory information after purchase
insert image description here
When the quantity of books in stock is 0, the book information of the stock information will be deleted automatically.
4. Create a trigger to automatically settle the amount of sales information

Sql 语句:
create trigger 结账金额 on 销售信息 for insert as 
    declare @图书价格 float
    declare @销售数量 int 
    declare @销售单号 nchar(10)
    declare @书号 nchar(10)
    select @销售数量=图书销售数量,@销售单号=销售单号,@书号=书号 from inserted
    select @图书价格=图书价格 from 图书信息 where @书号=书号
    update 销售信息 set 销售金额=@图书价格*@销售数量 where @销售单号=销售单号
go

Test sql statement:

insert into 销售信息 (销售单号,书号,顾客号,图书销售数量) values ('b2','001','1',2)

Sales information before testing
insert image description here
Execution result
insert image description here
5. Create a trigger to constrain the customer's gender (only male or female) and age (10-150 years old)

--对顾客性别进行约束
	create trigger 性别约束 on 顾客信息 for insert 
	as 
	declare @性别 nchar(20)
	declare @年龄 int
	select @性别=性别,@年龄= 年龄 from inserted
	if @性别!='男' and @性别!='女'
	begin
	print '性别格式错误!'
    Rollback TRANSACTION
	end
	if @年龄 not between 10 and 150
	begin
	print '年龄超出范围,必须在-150岁之间!'
    Rollback TRANSACTION
    end
	go

Test statement:

insert into 顾客信息 values ('5','王小壮','男',30,'1258468720')
insert into 顾客信息 values ('6','王大壮','男',9,'1258468720')

Customer information before test Test
insert image description here
result
insert image description here
insert image description here

Seven. python to sql server operation (implementation of embedded sql language)

In order to make the database more rationally used and connect its functions with reality, I wrote a small bookstore project in python high-level programming language, which uses embedded sql language and has basic addition, deletion, query and modification functions. The programming tool is pycharm. The main functions are as follows:

  1. purchase
  2. View/list books
  3. View/add suppliers
  4. View/add members
  5. Bill, please
  6. View purchase and sales records
  7. Check stock capacity
  8. leave

Let's talk about the main design principles of each function and the method of realizing the function.
insert image description here

1. Connect to the sql server database

First, you need to import the pymssql library, and then you can use some methods of database operation. At the same time, you need to create a user who can log in in the sql server. You need to use the pymssql.connect() method to connect to the database and fill in the database access address. (url), the user name and password of the database, the name of the database, and the port of the database. The default is 1433, but there are also active ports. Finally, the encoding format for reading must be written to prevent garbled characters.
code show as below:

# 数据库连接
import pymssql
    def sql_server_conn(self):
       connect = pymssql.connect(self.url, self.username, self.password, self.databaseName, port=self.port,charset=self.charset)  
# 服务器名,账户,密码,数据库名
        if connect:
            print(u"Success!!")
        return connect

2. Add, delete, check and modify functions

The addition, deletion and modification functions use the pymssql.execute() and pymssql.commit() methods, while the search uses the pymssql.execute() and pymssql.fetchall() methods. It is necessary to combine the relevant embedded SQL statements to operate the data information in the database. In order to ensure the rationality of the program, some exception captures must be set up, so that the process can be terminated normally when the SQL statement fails.
code show as below:

 # 执行sql语句,增删改查
    def execute_sql(self, sql):
        try:
            s1 = ''
            sql = sql.lower()
            if 'insert' in sql or 'delete' in sql or 'update' in sql:
                self.cursor.execute(sql)
                self.connect.commit()
                return
            elif 'select' in sql:
                self.cursor.execute(sql)
                rows = self.cursor.fetchall()
                for k in rows:
                    for k1 in k:
                        s1 += (str(k1).strip(' ')) + "\t\t"
                    s1 += '\n'
                if s1 == '':
                    print("无")
                print(s1)

        except :
            print("\033[1;31m 输入sql语句错误!自动返回菜单!\033[0m")


3. Other functions

Other functions are similar, except for the basic design of the sequence process, other operations on the database also use the above method of adding, deleting, checking and replacing. I won’t go into details one by one here, but a screenshot of the function running is given below.
insert image description here
insert image description here

insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

8. Summary

This course design took me a lot of time, but I also got a lot of things in it. I have learned SQL Server for half a semester, and I have not been so thorough again. First of all, I have systematically connected all parts of the SQL language. I am more familiar with triggers, cascading operations, stored procedures, and constraints, which make some messy data orderly. Of course, there is also a lot of attention to the design of the table. The structure of the table often determines the difficulty of subsequent design. I deeply understand this. When designing the bookstore management system, I found that there are some problems with my structure, which cannot be inserted directly. I wanted the data, so I changed it nearly 6 times later, and then I felt that the table structure was reasonable. This also taught me a lesson. When starting to import data, I must conceive the structure of the table.
Secondly, when implementing the embedded sql language, you need to connect to the sql server, which requires you to find some information on the Internet by yourself. At first, you couldn't connect, but finally found that it was a port problem. The problem caused some garbled characters. I solved it all night. It was an attribute data type problem, so I changed it to nchar type, which uses unicode encoding, and there will be no garbled characters. So I learned how to solve garbled characters Methods.

Nine. Source code

1. Complete sql statement

--创建数据库

create database bookshop

--建立基本表

	use bookshop
	create table 图书信息(
	书号 nchar(10) foreign key references 库存信息(书号),
	图书名称 nchar(20) NOT NULL ,
	图书类别 nchar(20) NOT NULL ,
	图书出版社 nchar(20) NOT NULL,
	图书价格 float not null,
	图书页数 int not null
)

create table 顾客信息(
	顾客号 nchar(10) NOT NULL PRIMARY KEY,
	姓名 nchar(20) NOT NULL,
	性别 nchar(20) NOT NULL,
	年龄 int NOT NULL,
	电话号码 nchar(20) not null,
	)
	create table 供应商信息(
	供应商号 nchar(10) NOT NULL PRIMARY KEY,
	供应商名称 nchar(20) NOT NULL,
	电话号码 nchar(20) NOT NULL,
	供应商地址 nchar(40) not null 
)

create table 进货信息(
	进货单号 nchar(10) NOT NULL PRIMARY KEY,
	书号 nchar(10) not NULL,
	图书类别 nchar(20) not NULL,
	供应商号 nchar(10) foreign key references 供应商信息(供应商号),
	图书进货数量 int NOT NULL,
	进货日期 date default (getdate())
)


create table 销售信息(
	销售单号 nchar(10) NOT NULL PRIMARY KEY,
	书号 nchar(10) foreign key references 库存信息(书号),
	顾客号 nchar(10) foreign key references 顾客信息(顾客号),
	图书销售数量 int NOT NULL,
	销售日期 date default (getdate()),
	销售金额 float null default (0)
)

create table 库存信息(
	书号 nchar(10) PRIMARY KEY, 
	图书类别 nchar(20) not null,
	图书数量 int not null
)


--添加数据

insert into 图书信息 values ('001','水浒传','中国古代小说','新华出版社',45.2,540)
insert into 图书信息 values ('002','战争与和平','外国小说','外国出版社',30.0,440)
insert into 图书信息 values ('003','三国演义','中国古代小说','新华出版社',45.5,540)
insert into 图书信息 values ('004','朝花夕拾','中国近代散文','新华出版社',30.1,540)
select * from 图书信息


insert into 顾客信息 values 
('1','王壮','男',30,'1258468720'),
('2','张力','男',35,'1845846872'),
('3','马超','男',20,'5896668720'),
('4','小红','女',18,'1598468720')
select * from 顾客信息
insert into 顾客信息 values 
('6','王小壮','男',30,'1258468720')


insert into 供应商信息 values 
('01','好再来','5265655','平顶山学院'),
('02','德利','5265655','平顶山学院'),
('03','华夏好书','5265655','平顶山学院'),
('04','武功秘籍','5265655','平顶山学院')
select * from 供应商信息

delete 供应商信息 where 供应商号='hjgh'
insert into 进货信息 (进货单号,书号,图书类别,供应商号,图书进货数量)values('a1','005','中国散文','01',20)
insert into 进货信息 (进货单号,书号,供应商号,图书进货数量)values('a2','002','外国小说','01',20)
insert into 进货信息 (进货单号,书号,供应商号,图书进货数量)values('a3','005','中国散文','01',20)
insert into 进货信息 (进货单号,书号,供应商号,图书进货数量)values('a4','001','中国古代小说','01',2) 
insert into 进货信息 (进货单号,书号,供应商号,图书进货数量)values('a5','005','中国散文','02',20) 
select * from 进货信息


insert into 销售信息 (销售单号,书号,顾客号,图书销售数量) values ('b2','001','1',2)
select * from 销售信息
delete from 销售信息

insert into 库存信息 values ('001','中国古代小说',10)
insert into 库存信息 values ('002','外国小说',20)
insert into 库存信息 values ('003','中国古代小说',20)
insert into 库存信息 values ('004','中国近代散文',20)
select * from 库存信息

delete 库存信息 where 书号='003'


-- 存储过程设置

--1. 创建存储过程查询某段时间内各种图书的进货和销售情况;
create procedure 进售信息
	@date1 date,
	@date2 date	
	AS
	select * from 进货信息 where 进货信息.进货日期>=@date1 and 进货信息.进货日期<=@date2
	select * from 销售信息 where 销售日期>=@date1 and 销售日期<=@date2
	go
	
	exec 进售信息 '2021-12-22','2021-12-23'
	drop procedure jx_list
	

-- 创建视图

--1. 创建视图查询各类图书的库存总数;

create view zl_numb 
as 
 select 图书类别,sum(图书数量) as 种类数量 from 库存信息 group by 图书类别
 go 

 select * from zl_numb
 
 
 --触发器
 
--1. 创建触发器当图书入库时自动修改相应图书的总量和存放仓库中该图书的数量;  
  -- 进货入库
	CREATE TRIGGER 库存增加 on 进货信息 for insert AS
	declare @num int
	declare @bnum nchar(10)
	declare @f  int
	declare @kinds nchar(20)
	select @num=图书进货数量,@bnum=书号,@kinds=图书类别 from inserted
	select @f=COUNT(@bnum)from 库存信息 where 书号=@bnum
	if @f>0
	begin
	update 库存信息 set 图书数量=图书数量+@num where 书号=@bnum
	end
	if @f<=0
	begin
		insert into 库存信息 values (@bnum,@kinds,@num)
	end
	go
	
	drop trigger 库存增加
--销售出库
	CREATE TRIGGER 库存减少 on 销售信息 for insert AS
		declare @num int
		declare @bnum nchar(10)
		declare @num1 int
		select @num=图书销售数量,@bnum=书号 from inserted
		select @num1=图书数量 from 库存信息 where @bnum=书号
		if @num1 <= @num
			begin
			if @num1=@num
			begin
			delete 库存信息 where 书号=@bnum
			end
			else
			begin
			print '销售失败,图书数量不够!'
			Rollback TRANSACTION
			end
			end
		else
			begin
			update 库存信息 set 图书数量=图书数量-@num where 书号=@bnum
			end
		go


-- 自动填入金钱数量

    create trigger 结账金额 on 销售信息 for insert as 
    declare @图书价格 float
    declare @销售数量 int 
    declare @销售单号 nchar(10)
    declare @书号 nchar(10)
    select @销售数量=图书销售数量,@销售单号=销售单号,@书号=书号 from inserted
    select @图书价格=图书价格 from 图书信息 where @书号=书号
    update 销售信息 set 销售金额=@图书价格*@销售数量 where @销售单号=销售单号
    go
    
	
	--对顾客性别进行约束
	create trigger 性别约束 on 顾客信息 for insert 
	as 
	declare @性别 nchar(20)
	declare @年龄 int
	select @性别=性别,@年龄= 年龄 from inserted
	if @性别!='男' and @性别!='女'
	begin
	print '性别格式错误!'
    Rollback TRANSACTION
	end
	if @年龄 not between 10 and 150
	begin
	print '年龄超出范围,必须在-150岁之间!'
    Rollback TRANSACTION
    end
	go
	
--设置完整性约束
--设置销售金额默认值是
alter table 销售信息 add default(0) for 销售金额
--设置级联删除更新,当库存信息中书号改变,图书信息中的学号也改变,当库存信息中数据删除时,图书中的数据也级联删除
alter table 图书信息 add constraint 库存删除 foreign key(书号) references 库存信息(书号) on delete CASCADE on update cascade
--设置库存信息和销售信息级联更新
alter table 销售信息 add constraint 销售更新 foreign key(书号) references 库存信息(书号) on update cascade 
--进货信息与库存信息之间级联删除更新
alter table 进货信息 add constraint 进货删除 foreign key(书号) references 库存信息(书号) on delete CASCADE on update cascade
--进货信息和供应商信息设置级联删除更新,使数据保持一致
alter table 进货信息 add constraint 供应商删除 foreign key(供应商号) references 供应商信息(供应商号) on delete CASCADE on update cascade
--销售信息与顾客信息建立级联删除,并在顾客号上,建立级联更新,以便数据更改。
alter table 销售信息 add constraint 顾客删除 foreign key(顾客号) references 顾客信息(顾客号) on delete CASCADE on update cascade

2. Python source code

# import pymssql
# serverName = '127.0.0.1'    #目的主机ip地址
# userName = 'zpx'        #SQL Server身份账号
# passWord = '123'        #SQL Server身份密码
# dbName = 'bookshop'        #对应数据库名称
# connect = pymssql.connect(serverName,userName, passWord,dbName,port='49680') #SQL Server身份验证建立连接
# # connect = pymssql.connect(server = serverName , database = dbName) #Window默认身份验证建立连接
#
# if connect:
#     print("连接成功!")

import pymssql
import msvcrt
from pykeyboard import *
import time
import traceback, sys

import switch as switch


class database(object):
    """数据库操作对象"""

    def __init__(self, url, username, password, databaseName, port, charset):
        self.url = url
        self.username = username
        self.password = password
        self.databaseName = databaseName
        self.port = port
        self.charset = charset
        self.connect = self.sql_server_conn()
        self.cursor = self.connect.cursor()

    def sql_server_conn(self):
        connect = pymssql.connect(self.url, self.username, self.password, self.databaseName, port=self.port,
                                  charset=self.charset)  # 服务器名,账户,密码,数据库名
        if connect:
            print(u"Success!!")
        return connect

    # 查看表的所有字段,
    # @table_name :表名
    def get_column_name(self, table_name):
        self.cursor.execute("select top 1 * from " + table_name)  # 执行sql语句
        data_dict = []
        for field in self.cursor.description:
            data_dict.append(field[0])
        print(data_dict)
        return data_dict

    # 得到数据库所有的表名
    def get_table_name(self):
        sql = "SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' ORDER BY NAME"
        self.cursor.execute(sql)  # 返回执行成功的结果条数
        rows = self.cursor.fetchall()
        for d in rows:
            for k in d:
                print(k)

    # 执行sql语句,增删改查
    # @sql:sql语句
    def execute_sql(self, sql):
        try:
            s1 = ''
            sql = sql.lower()
            if 'insert' in sql or 'delete' in sql or 'update' in sql:
                self.cursor.execute(sql)
                self.connect.commit()
                return
            elif 'select' in sql:
                self.cursor.execute(sql)
                rows = self.cursor.fetchall()
                print("进货单号\t书号\t\t图书类型\t\t供应商号\t图书进货数量\t进货日期")
                for k in rows:
                    for k1 in k:
                        s1 += (str(k1).strip(' ')) + "\t\t"
                    s1 += '\n'
                if s1 == '':
                    print("无")
                print(s1)

        except :
            print("\033[1;31m 输入sql语句错误!自动返回菜单!\033[0m")

    def InGoods(self):
        # 先确定进货单号,再进货
        sql = 'select 进货单号 from 进货信息'
        s=''
        self.cursor.execute(sql)
        rows = self.cursor.fetchall()
        for k in rows:
            for k1 in k:
                s += (str(k1).strip(' ')) + " "
        print("已有进货单号:")
        if s == '':
            print("无")
        print(s)
        num = input("请输入进货单号:")
        bnum=input("请输入书号:")
        kinds = input("请输入图书类型:")
        inshopnum=input("请输入供应商号:")
        snum=input("请输入图书进货数量:")
        sql = "insert into 进货信息(进货单号,书号,图书类别,供应商号,图书进货数量) values ('" + num + "','" + bnum+ "','" + kinds+"','" + inshopnum + "',"+ snum+" )"
        self.execute_sql(sql)

    def sale(self):
        chose=input("你是要查看,还是添加? C/A")
        s = ''
        if chose == 'A' or chose == 'a':
            sql = 'select 书号 from 图书信息'
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            for k in rows:
                for k1 in k:
                    s += (str(k1).strip(' ')) + " "
            print("已上架书号:")
            if s=='':
                print("无")
            print(s)
            sql = 'select 书号 from 库存信息'
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            for k in rows:
                for k1 in k:
                    s += (str(k1).strip(' ')) + " "
            print("库存内书号:")
            if s == '':
                print("无")
            print(s)
            num = input("请输入要上架书号:")
            bname = input("请输入图书名:")
            kinds = input("请输入图书类别:")
            cbs = input("请输入图书出版社:")
            price = input("请输入图书价格:")
            ynum = input("请输入图书页数:")
            sql = "insert into 图书信息 values ('" + num + "','" + bname + "','" + kinds + "','" + cbs + "'," + price + "," + ynum + ")"
            print("正在上架...")
            if self.execute_sql(sql):
                print("上架成功")
        if chose == 'c' or chose == 'C':
            s1 = ''
            bnum = input("请输入书号:")
            sql = "select * from 图书信息 where 书号= '" + bnum + "'"
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            print("书号\t图书名称\t 图书类别\t图书出版社\t图书价格\t图书页数")
            for k in rows:
                for k1 in k:
                    s1 += (str(k1).strip(' ')) + "\t"
                s1 += '\n'
            if s1 == '':
                print("无此图书")
            print(s1)

    def InShoper(self):
        chose=input("你是要查看,还是添加? C/A:")
        sql = 'select 供应商号 from 供应商信息'
        s = ''
        if chose=='A' or chose=='a':
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            for k in rows:
                for k1 in k:
                    s += (str(k1).strip(' ')) + " "
            print("已有供应商号:")
            if s == '':
                print("无")
            print(s)
            num = input("请输入供应商号:")
            name = input("请输入供应商名称:")
            tel = input("请输入供应商电话:")
            add = input("请输入供应商地址:")
            # sql=('insert into 供应商信息 values (%s,%s,%s,%s)'%(num,name,tel,add))
            sql = "insert into 供应商信息 values ('" + num + "','" + name + "','" + tel + "','" + add + "')"
            con.execute_sql(sql)
            chose='C'
        elif chose=='c' or chose=='C':
            s1 = ''
            self.cursor.execute('select * from 供应商信息')
            rows = self.cursor.fetchall()
            print('现有供应商如下:')
            print("供应商号\t供应商名称\t供应商电话\t供应商地址")
            for k in rows:
                for k1 in k:
                    s1 += (str(k1).strip(' ')) + "\t\t"
                s1 += '\n'
            if s1 == '':
                print("无")
            print(s1)
        else:
            print("输入错误!")
    def Customer(self):
        chose = input("你是要查看,还是添加? C/A:")
        sql = 'select 顾客号 from 顾客信息'
        s = ''
        if chose == 'A' or chose == 'a':
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            for k in rows:
                for k1 in k:
                    s += (str(k1).strip(' ')) + " "
            print("已有顾客号:")
            if s == '':
                print("无")
            print(s)
            num = input("请输入顾客号:")
            name = input("请输入顾客姓名:")
            tel = input("请输入顾客电话:")
            age = input("请输入顾客年龄: ")
            sex = input("请输入顾客性别:")
            # sql=('insert into 供应商信息 values (%s,%s,%s,%s)'%(num,name,tel,add))
            sql = "insert into 顾客信息 values ('" + num + "','" + name + "','" + sex + "'," + age + ",'" + tel + "')"
            # print(sql)
            con.execute_sql(sql)
        if chose == 'c' or chose == 'C':
            s1 = ''
            gknum=input("请输入顾客号:")
            sql="select * from 顾客信息 where 顾客号= '"+gknum+"'"
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            print("顾客号\t顾客姓名\t顾客性别\t顾客年龄\t\t顾客电话")
            for k in rows:
                for k1 in k:
                    s1 += (str(k1).strip(' ')) + "\t\t"
                s1 += '\n'
            if s1 == '':
                print("无")
            print(s1)

    def CheckOut(self):
        sql = 'select 销售单号 from 销售信息'
        s = ''
        self.cursor.execute(sql)
        rows = self.cursor.fetchall()
        for k in rows:
            for k1 in k:
                s += (str(k1).strip(' ')) + " "
        print("已用销售单号:")
        if s == '':
            print("无")
        print(s)
        num = input("请输入销售单号:")
        name = input("请输入书号:")
        uname = input("请输入顾客号:")
        add = input("请输入销售图书数量:")
        # sql=('insert into 供应商信息 values (%s,%s,%s,%s)'%(num,name,tel,add))
        sql = "insert into 销售信息(销售单号,书号,顾客号,图书销售数量) values ('" + num + "','" + name + "','" + uname + "'," + add + ")"
        # print(sql)
        con.execute_sql(sql)
        s1 = ''
        try:
            sql="select 销售金额 from 销售信息 where 销售单号= '"+num+"'"
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
        except:
            print("sql语句错误!")
        for k in rows:
            for k1 in k:
                s1=(str(k1).strip(' '))
        print("应付金额 :"+s1)
    def record(self):
        chose= input("查看哪个记录?1.进货记录 2.销售记录:")
        if chose=='1':
            s1=''
            sql = 'select * from 进货信息'
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            print("进货单号\t书号\t\t图书类别\t\t供应商号\t图书进货数量\t进货日期")
            for k in rows:
                for k1 in k:
                    s1 += (str(k1).strip(' ')) + "\t\t"
                s1 += '\n'
            if s1 == '':
                print("无")
            print(s1)
        if chose=='2':
            s1 = ''
            sql = 'select * from 销售信息'
            self.cursor.execute(sql)
            rows = self.cursor.fetchall()
            print("销售单号\t书号\t 顾客号\t图书销售数\t销售日期\t\t  销售金额")
            for k in rows:
                for k1 in k:
                    s1 += (str(k1).strip(' ')) + "\t\t"
                s1 += '\n'
            if s1 == '':
                print("无")
            print(s1)
        else:
            print("输入错误!")

    def Stock(self):
        s1 = ''
        sql = 'select * from 库存信息'
        self.cursor.execute(sql)
        rows = self.cursor.fetchall()
        print("书号\t\t图书类别 \t库存量")
        for k in rows:
            for k1 in k:
                s1 += (str(k1).strip(' ')) + "\t\t"
            s1 += '\n'
        if s1 == '':
            print("无")
        print(s1)


    def menu(self):
        print("欢迎来到书店!")
        while True:
            print("服务菜单如下:")
            print('1.进货')
            print('2.查看/上架图书')
            print('3.查看/新增供应商')
            print('4.查看/新增会员')
            print('5.结账')
            print('6.查看进货和销售记录')
            print('7.查看库存容量')
            print('0.离开')
            key = input("请选择需要的服务:")
            if key == '1':
                con.InGoods()
                input("按回车继续")

            elif key == '2':
                con.sale()
                input("按回车继续")

            elif key == '3':
                con.InShoper()
                input("按回车继续")

            elif key == '4':
                con.Customer()
                input("按回车继续")

            elif key == '5':
                con.CheckOut()
                input("按回车继续")

            elif key == '6':
                con.record()
                input("按回车继续")

            elif key == '7':
                con.Stock()
                input("按回车继续")

            elif key == '0':
                exit_course = input('确定退出吗?(y/n):')
                if exit_course == 'y' or exit_course=='Y':
                    exit()
                else:
                    pass
            else:
                print("请输入正确的数值!")

    # 关闭游标,连接
    def close(self):
        self.cursor.close()  # 关闭游标
        self.connect.close()


if __name__ == '__main__':
    con = database('127.0.0.1', 'zpx', '123', 'bookshop', '49680', 'utf8')
    # con.execute_sql("select * from 进货信息")
    # con.InShoper()
    # con.sale()
    # con.Customer()
    con.menu()

Guess you like

Origin blog.csdn.net/Tom197/article/details/122378443