ADD file via upload

master
xtu202105570126 2 years ago
parent 28bfa41367
commit 28c236afd7

@ -0,0 +1,628 @@
import sys
import sqlite3
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QLineEdit, QPushButton, \
QMessageBox
from PySide6.QtSql import QSqlDatabase, QSqlQuery
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QLineEdit, QPushButton, \
QMessageBox, QPlainTextEdit
from PySide6.QtWidgets import QDialog
# 创建数据库连接
conn = sqlite3.connect('students.db')
# 创建学生表
conn.execute('''CREATE TABLE IF NOT EXISTS students
(name TEXT NOT NULL,
student_number INTEGER NOT NULL,
score INTEGER NOT NULL)''')
# 创建用户表
conn.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL)''')
# 创建图书列表表
conn.execute('''CREATE TABLE IF NOT EXISTS books
(book_id INTEGER PRIMARY KEY,
book_name TEXT NOT NULL,
book_status TEXT NOT NULL)''')
class LoginWindow(QWidget):
def __init__(self):
super().__init__()
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('students.db')
self.db.open()
self.createTable()
self.username = QLineEdit()
self.password = QLineEdit()
self.password.setEchoMode(QLineEdit.Password)
login_button = QPushButton('登录')
login_button.clicked.connect(self.login)
register_button = QPushButton('注册')
register_button.clicked.connect(self.register)
layout = QVBoxLayout()
layout.addWidget(QLabel("账号:"))
layout.addWidget(self.username)
layout.addWidget(QLabel("密码:"))
layout.addWidget(self.password)
layout.addWidget(login_button)
layout.addWidget(register_button)
self.setLayout(layout)
def login(self):
username = self.username.text()
password = self.password.text()
if not username or not password:
QMessageBox.warning(self, '错误', '账号密码不能为空')
return
query = QSqlQuery(self.db)
query.exec("SELECT * FROM users WHERE username='%s' AND password='%s'" % (username, password))
if query.next():
self.hide()
is_admin = username == 'van' # 检查是否为管理员
self.window = StudentApp(username, is_admin) # 传递用户名和管理员参数
self.window.show()
else:
QMessageBox.warning(self, '错误', '账号或密码错误')
self.password.clear()
def register(self):
username = self.username.text()
password = self.password.text()
if not username or not password:
QMessageBox.warning(self, '错误', '账号和密码不能为空')
return
query = QSqlQuery(self.db)
query.exec(f"SELECT * FROM users WHERE username='{username}'")
if query.next():
QMessageBox.warning(self, '错误', '该账户已经存在')
return
query.prepare("INSERT INTO users (username, password) VALUES (?, ?)")
query.bindValue(0, username)
query.bindValue(1, password)
if query.exec():
QMessageBox.information(self, '成功', '你已成功注册')
else:
QMessageBox.warning(self, '错误', '注册失败')
def createTable(self):
query = QSqlQuery(self.db)
query.exec("CREATE TABLE IF NOT EXISTS users (username varchar(20), password varchar(20))")
# 添加管理员账号
query.exec("SELECT * FROM users WHERE username='van'")
if not query.next():
query.prepare("INSERT INTO users (username, password) VALUES (?, ?)")
query.bindValue(0, 'van')
query.bindValue(1, '123456')
query.exec()
class StudentApp(QMainWindow):
def __init__(self, username, is_admin): # 接收用户名和管理员参数
super().__init__()
self.username = username # 保存用户名
self.is_admin = is_admin # 保存管理员状态
self.setWindowTitle(f'学生信息管理 - {username}') # 设置窗口标题为用户名
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout()
welcome_label = QLabel(f'你好,{username}') # 显示欢迎消息
layout.addWidget(welcome_label)
self.name_label = QLabel("姓名:")
self.name_edit = QLineEdit()
layout.addWidget(self.name_label)
layout.addWidget(self.name_edit)
self.student_number_label = QLabel("学号:")
self.student_number_edit = QLineEdit()
layout.addWidget(self.student_number_label)
layout.addWidget(self.student_number_edit)
self.score_label = QLabel("成绩:")
self.score_edit = QLineEdit()
layout.addWidget(self.score_label)
layout.addWidget(self.score_edit)
self.add_student_btn = QPushButton('添加学生信息')
self.add_student_btn.clicked.connect(self.add_student)
layout.addWidget(self.add_student_btn)
self.find_student_btn = QPushButton('查找学生信息')
self.find_student_btn.clicked.connect(self.find_student)
layout.addWidget(self.find_student_btn)
self.delete_student_btn = QPushButton('删除学生信息')
self.delete_student_btn.clicked.connect(self.delete_student)
layout.addWidget(self.delete_student_btn)
self.clear_table_btn = QPushButton('清空表数据')
self.clear_table_btn.clicked.connect(self.clear_table)
layout.addWidget(self.clear_table_btn)
self.sort_by_score_btn = QPushButton('按成绩排序')
self.sort_by_score_btn.clicked.connect(self.sort_by_score)
layout.addWidget(self.sort_by_score_btn)
self.sort_by_student_number_btn = QPushButton('按学号排序')
self.sort_by_student_number_btn.clicked.connect(self.sort_by_student_number)
layout.addWidget(self.sort_by_student_number_btn)
self.library_system_btn = QPushButton('图书管理系统')
self.library_system_btn.clicked.connect(self.open_library_system)
layout.addWidget(self.library_system_btn)
self.output_label = QLabel("操作结果:")
self.output_text = QPlainTextEdit()
self.output_text.setReadOnly(True)
layout.addWidget(self.output_label)
layout.addWidget(self.output_text)
self.manage_users_btn = QPushButton('管理登录用户')
self.manage_users_btn.clicked.connect(self.manage_users)
layout.addWidget(self.manage_users_btn)
self.change_password_btn = QPushButton('修改密码')
self.change_password_btn.clicked.connect(self.change_password)
layout.addWidget(self.change_password_btn)
self.logout_btn = QPushButton('退出')
self.logout_btn.clicked.connect(self.logout)
layout.addWidget(self.logout_btn)
central_widget.setLayout(layout)
if not is_admin:
self.add_student_btn.setEnabled(False)
self.delete_student_btn.setEnabled(False)
self.clear_table_btn.setEnabled(False)
self.show()
def manage_users(self):
if self.is_admin:
self.manage_users_window = ManageUsersWindow()
self.manage_users_window.show()
else:
QMessageBox.warning(self, '权限错误', '您无权访问')
def change_password(self):
self.change_password_window = ChangePasswordWindow(self.username, self)
self.change_password_window.show()
def open_library_system(self):
self.library_system = LibrarySystemWindow(self.username,self.is_admin) # 传递当前登录用户的用户名
self.library_system.show()
def add_student(self):
name = self.name_edit.text()
student_number = self.student_number_edit.text()
score = self.score_edit.text()
if not name or not student_number or not score:
QMessageBox.warning(self, '输入错误', '姓名、学号和成绩不能为空')
return
cursor = conn.execute("SELECT * FROM students WHERE student_number=?", (student_number,))
existing_student = cursor.fetchone()
if existing_student:
self.output_text.setPlainText("已存在该学号的学生信息!")
return
conn.execute("INSERT INTO students (name, student_number, score) VALUES (?, ?, ?)",
(name, student_number, score))
conn.commit()
self.output_text.setPlainText("学生信息已添加成功!")
self.clear_inputs()
def find_student(self):
student_number = self.student_number_edit.text()
name = self.name_edit.text()
if not student_number and not name:
QMessageBox.warning(self, '输入错误', '姓名和学号不能同时为空')
return
cursor = conn.execute("SELECT name, student_number, score FROM students WHERE name=? OR student_number=?",
(name, student_number))
students = cursor.fetchall()
if students:
if student_number and name: # 如果姓名和学号都输入了
name_matched = False
for student in students:
if str(student_number) == str(student[1]) and name == student[0]:
name_matched = True
break
if not name_matched:
self.output_text.setPlainText("学号与姓名不匹配!")
self.name_edit.clear()
self.student_number_edit.clear()
return
self.output_text.setPlainText("学生信息:\n")
count = 1
for student in students:
self.output_text.appendPlainText(f"编号: {count}")
self.output_text.appendPlainText("姓名: " + student[0])
self.output_text.appendPlainText("学号: " + str(student[1]))
self.output_text.appendPlainText("成绩: " + str(student[2]))
self.output_text.appendPlainText("------------------")
count += 1
else:
self.output_text.setPlainText("未找到学生信息!")
self.name_edit.clear()
def delete_student(self):
student_number = self.student_number_edit.text()
cursor = conn.execute("SELECT * FROM students WHERE student_number=?", (student_number,))
student = cursor.fetchone()
if student:
conn.execute("DELETE FROM students WHERE student_number=?", (student_number,))
conn.commit()
self.output_text.setPlainText("学生信息已删除!")
self.clear_inputs()
else:
self.output_text.setPlainText("未找到学生信息!")
def clear_table(self):
conn.execute("DELETE FROM students")
conn.commit()
self.output_text.setPlainText("表数据已清空!")
self.clear_inputs()
def sort_by_score(self):
cursor = conn.execute("SELECT name, student_number, score FROM students ORDER BY score DESC")
students = cursor.fetchall()
self.display_students(students)
def sort_by_student_number(self):
cursor = conn.execute("SELECT name, student_number, score FROM students ORDER BY student_number ASC")
students = cursor.fetchall()
self.display_students(students)
def display_students(self, students):
if students:
self.output_text.setPlainText("学生信息:\n")
count = 1
for student in students:
self.output_text.appendPlainText(f"编号: {count}")
self.output_text.appendPlainText("姓名: " + student[0])
self.output_text.appendPlainText("学号: " + str(student[1]))
self.output_text.appendPlainText("成绩: " + str(student[2]))
self.output_text.appendPlainText("------------------")
count += 1
else:
self.output_text.setPlainText("数据库中没有学生信息!")
def clear_inputs(self):
self.name_edit.clear()
self.student_number_edit.clear()
self.score_edit.clear()
def logout(self):
self.close()
login_window.show()
class ChangePasswordWindow(QDialog):
def __init__(self, username, parent=None):
super().__init__(parent)
self.setWindowTitle("修改密码")
self.username = username
self.old_password_edit = QLineEdit()
self.old_password_edit.setEchoMode(QLineEdit.Password)
self.new_password_edit = QLineEdit()
self.new_password_edit.setEchoMode(QLineEdit.Password)
save_button = QPushButton("保存")
save_button.clicked.connect(self.change_password)
layout = QVBoxLayout()
layout.addWidget(QLabel("旧密码:"))
layout.addWidget(self.old_password_edit)
layout.addWidget(QLabel("新密码:"))
layout.addWidget(self.new_password_edit)
layout.addWidget(save_button)
self.setLayout(layout)
def change_password(self):
old_password = self.old_password_edit.text()
new_password = self.new_password_edit.text()
query = QSqlQuery()
query.exec(f"SELECT * FROM users WHERE username='{self.username}' AND password='{old_password}'")
if query.next():
query.prepare("UPDATE users SET password=? WHERE username=?")
query.bindValue(0, new_password)
query.bindValue(1, self.username)
if query.exec():
QMessageBox.information(self, "成功", "密码修改成功")
self.close()
else:
QMessageBox.warning(self, "失败", "密码修改失败")
else:
QMessageBox.warning(self, "失败", "旧密码错误")
class ManageUsersWindow(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('管理登录用户')
self.setMinimumWidth(400)
self.search_username_edit = QLineEdit()
self.search_username_edit.setPlaceholderText('输入用户名')
self.search_username_button = QPushButton('搜索')
self.search_username_button.clicked.connect(self.search_username)
self.delete_user_button = QPushButton('删除该账户')
self.delete_user_button.clicked.connect(self.delete_user)
self.show_all_users_button = QPushButton('显示所有的用户')
self.show_all_users_button.clicked.connect(self.show_all_users)
self.output_text = QPlainTextEdit()
self.output_text.setReadOnly(True)
layout = QVBoxLayout()
layout.addWidget(QLabel('搜索账号:'))
layout.addWidget(self.search_username_edit)
layout.addWidget(self.search_username_button)
layout.addWidget(self.show_all_users_button)
layout.addWidget(self.delete_user_button)
layout.addWidget(QLabel('用户列表:'))
layout.addWidget(self.output_text)
self.setLayout(layout)
def search_username(self):
username = self.search_username_edit.text()
if not username:
QMessageBox.warning(self, '错误', '请输入用户名')
return
query = QSqlQuery()
query.exec(f"SELECT * FROM users WHERE username='{username}'")
if query.next():
password = query.value(2)
self.output_text.setPlainText(f'用户名: {username}\n密码: {password}')
else:
self.output_text.setPlainText('未找到该用户')
def show_all_users(self):
query = QSqlQuery()
query.exec('SELECT * FROM users')
users = []
while query.next():
username = query.value(1)
password = query.value(2)
users.append(f'用户名: {username}\n密码: {password}\n')
users.append('------------------\n')
if users:
self.output_text.setPlainText(''.join(users))
else:
self.output_text.setPlainText('用户表为空')
def delete_user(self):
username = self.search_username_edit.text()
if not username:
QMessageBox.warning(self, '错误', '请输入用户名')
return
query = QSqlQuery()
query.exec(f"SELECT * FROM users WHERE username='{username}'")
if query.next():
query.exec(f"DELETE FROM users WHERE username='{username}'")
self.output_text.setPlainText(f'已删除账户: {username}')
self.search_username_edit.clear()
else:
self.output_text.setPlainText('未找到该用户')
class LibrarySystemWindow(QMainWindow):
def __init__(self, username,is_admin):
super().__init__()
self.setWindowTitle('图书管理系统')
self.username = username # 保存用户名
self.is_admin=is_admin
central_widget = QWidget()
self.setCentralWidget(central_widget)
layout = QVBoxLayout()
self.book_id_label = QLabel("图书编号:")
self.book_id_edit = QLineEdit()
layout.addWidget(self.book_id_label)
layout.addWidget(self.book_id_edit)
self.book_name_label = QLabel("图书名称:")
self.book_name_edit = QLineEdit()
layout.addWidget(self.book_name_label)
layout.addWidget(self.book_name_edit)
self.borrow_btn = QPushButton('借出')
self.borrow_btn.clicked.connect(self.borrow_book)
layout.addWidget(self.borrow_btn)
self.return_btn = QPushButton('还书')
self.return_btn.clicked.connect(self.return_book)
layout.addWidget(self.return_btn)
self.add_book_btn = QPushButton('添加图书')
self.add_book_btn.clicked.connect(self.add_book)
layout.addWidget(self.add_book_btn)
self.find_book_btn = QPushButton('查找图书')
self.find_book_btn.clicked.connect(self.find_book)
layout.addWidget(self.find_book_btn)
self.delete_book_btn = QPushButton('删除图书')
self.delete_book_btn.clicked.connect(self.delete_book)
layout.addWidget(self.delete_book_btn)
self.show_all_books_btn = QPushButton('显示所有图书')
self.show_all_books_btn.clicked.connect(self.show_all_books)
layout.addWidget(self.show_all_books_btn)
self.output_label = QLabel("操作结果:")
self.output_text = QPlainTextEdit()
self.output_text.setFixedSize(400, 300)
self.output_text.setReadOnly(True)
layout.addWidget(self.output_label)
layout.addWidget(self.output_text)
central_widget.setLayout(layout)
def open_library_system(self):
self.library_system = LibrarySystemWindow(self.username)
self.library_system.show()
def add_book(self):
if not self.is_admin:
self.output_text.setPlainText("您无权限执行该操作!")
return
book_id = self.book_id_edit.text()
book_name = self.book_name_edit.text()
cursor = conn.execute("SELECT * FROM books WHERE book_id=?", (book_id,))
existing_book = cursor.fetchone()
if existing_book:
self.output_text.setPlainText("已存在该图书编号的图书!")
self.clear_inputs()
return
conn.execute("INSERT INTO books (book_id, book_name, book_status) VALUES (?, ?, '未借出')",
(book_id, book_name))
conn.commit()
self.output_text.setPlainText("图书已成功添加!")
self.clear_inputs()
def borrow_book(self):
book_id = self.book_id_edit.text()
cursor = conn.execute("SELECT * FROM books WHERE book_id=?", (book_id,))
book = cursor.fetchone()
if book:
book_status = book[2]
if "未借出" in book_status:
borrower = self.username # 使用登录界面的账号作为借书人
updated_status = "已借出 by " + borrower
conn.execute("UPDATE books SET book_status=? WHERE book_id=?", (updated_status, book_id))
conn.commit()
self.output_text.setPlainText("图书已成功借出!")
self.clear_inputs()
else:
self.output_text.setPlainText("图书已借出,无法再次借阅!")
self.clear_inputs()
else:
self.output_text.setPlainText("未找到图书信息!")
self.clear_inputs()
self.clear_inputs()
def return_book(self):
book_id = self.book_id_edit.text()
cursor = conn.execute("SELECT * FROM books WHERE book_id=?", (book_id,))
book = cursor.fetchone()
if book:
if "未借出" in book[2]:
self.output_text.setPlainText("您未借阅该图书!")
else:
borrower = book[2].split("by ")[1] # 获取当前借书人
if borrower == self.username: # 判断是否为当前用户借出的书
updated_status = "未借出" # 设置为未借出状态
conn.execute("UPDATE books SET book_status=? WHERE book_id=?", (updated_status, book_id))
conn.commit()
self.output_text.setPlainText("图书已成功归还!")
self.clear_inputs()
else:
self.output_text.setPlainText("您无需归还该书!")
self.clear_inputs()
else:
self.output_text.setPlainText("未找到图书信息!")
self.clear_inputs()
def find_book(self):
book_id = self.book_id_edit.text()
book_name = self.book_name_edit.text()
if not book_id and not book_name:
QMessageBox.warning(self, '输入错误', '图书编号和图书名称不能同时为空')
return
cursor = conn.execute("SELECT book_id, book_name, book_status FROM books WHERE book_id=? OR book_name=?",
(book_id, book_name))
books = cursor.fetchall()
if books:
if book_id and book_name: # 如果图书编号和图书名称都输入了
name_matched = False
for book in books:
if str(book_id) == str(book[0]) and book_name == book[1]:
name_matched = True
break
if not name_matched:
self.output_text.setPlainText("图书名称与编号不匹配!")
self.clear_inputs()
return
self.output_text.setPlainText("图书信息:\n")
for book in books:
self.output_text.appendPlainText("图书编号: " + str(book[0]))
self.output_text.appendPlainText("图书名称: " + book[1])
self.output_text.appendPlainText("图书借出情况: " + book[2])
self.output_text.appendPlainText("------------------")
else:
self.output_text.setPlainText("未找到图书信息!")
self.clear_inputs()
def delete_book(self):
if not self.is_admin:
self.output_text.setPlainText("您无权限执行该操作!")
return
book_id = self.book_id_edit.text()
cursor = conn.execute("SELECT * FROM books WHERE book_id=?", (book_id,))
book = cursor.fetchone()
if book:
conn.execute("DELETE FROM books WHERE book_id=?", (book_id,))
conn.commit()
self.output_text.setPlainText("图书已成功删除!")
self.clear_inputs()
else:
self.output_text.setPlainText("未找到图书信息!")
def show_all_books(self):
cursor = conn.execute("SELECT * FROM books")
books = cursor.fetchall()
if books:
self.output_text.setPlainText("所有图书信息:\n")
for book in books:
self.output_text.appendPlainText("图书编号: " + str(book[0]))
self.output_text.appendPlainText("图书名称: " + book[1])
self.output_text.appendPlainText("图书借出情况: " + book[2])
self.output_text.appendPlainText("-----------------------------")
else:
self.output_text.setPlainText("图书列表为空!")
def return_to_student_app(self):
self.parent().show()
self.close()
def clear_inputs(self):
self.book_id_edit.clear()
self.book_name_edit.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
login_window = LoginWindow()
login_window.show()
sys.exit(app.exec())
Loading…
Cancel
Save