代码实现(校园一卡通管理系统)

  这个项目依旧选择用Python+PyQt5来进行开发,数据库部分则选择使用mysql。

  我主要负责实现主窗口部分的学生基本信息栏和交易记录栏的增删改查、批量插入、批量删除等功能,同时负责部分UI界面的制作以及后端mysql数据库交互方法的编写等。

目录

  • 代码实现(校园一卡通管理系统)
    • 一、主函数(main.py)
    • 二、登录窗口(LoginWindow.py)
    • 三、忘记密码窗口(ForgetWindow.py)
    • 四、主窗口(MainWindow.py)(重点)
      • 1. 成员变量
      • 2. 构造函数
      • 3. 更新选择区域
      • 4. 便捷修改记录
      • 5. 更新标记 & 发射信号
      • 6. 单个删除 & 批量删除
      • 7. 下拉框元素更新
      • 8. 模糊查找
      • 9. 更新交易记录
      • 10. 充值
    • 五、单条插入窗口(InsertWindow.py)
    • 六、批量导入窗口(BatchInsertedWindow.py)
    • 七、与数据库交互的各种方法(Functions.py)

一、主函数(main.py)

  主函数用来创建各个窗口,并且建立各个窗口之间的关系。

from PyQt5.QtWidgets import QApplicationfrom BatchInsertedWindow import BatchInsertedWindow
from ForgetWindow import ResetWindow, SecurityQuestionWindow
from LoginWindow import LoginWindow
from MainWindow import MainWindow
from InsertWindow import InsertWindow
import sysif __name__ == "__main__":app = QApplication(sys.argv)login_widget = LoginWindow()  # 窗口控件login_widget.show()main_widget = MainWindow()  # 窗口控件forget_widget = SecurityQuestionWindow()  # 密保窗口reset_widget = ResetWindow()  # 重置密码窗口insert_widget = InsertWindow()  # 窗口控件batch_insert_widget = BatchInsertedWindow()  # 批量插入窗口login_widget.signal.connect(main_widget.show)  # 连接槽函数login_widget.forget_signal.connect(forget_widget.show)  # 显示忘记密码窗口forget_widget.signal.connect(reset_widget.show)  # 显示重置密码窗口forget_widget.back_signal.connect(login_widget.show)  # 显示登录窗口reset_widget.signal.connect(login_widget.show)  # 回到登录窗口reset_widget.back_signal.connect(login_widget.show)  # 回到登录窗口main_widget.batch_signal.connect(batch_insert_widget.show)  # 显示批量插入窗口main_widget.insert_signal.connect(insert_widget.show)  # 连接槽函数insert_widget.inserted_signal.connect(main_widget.query)  # 更新数据sys.exit(app.exec_())

二、登录窗口(LoginWindow.py)

  登录窗口负责用户身份验证,以及弹出忘记密码窗口等功能。

from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import ctypes
from PyQt5.QtWidgets import QMainWindow, QLineEdit, QMessageBox, QWidgetfrom Functions import load
from Login_UI import Ui_LoginWindowclass LoginWindow(QtWidgets.QMainWindow, Ui_LoginWindow):signal = pyqtSignal()forget_signal = pyqtSignal()def __init__(self):super().__init__()self.setupUi(self)self.setWindowTitle('校园一卡通管理系统登录')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标# self.setStyleSheet('QWidget{background-color:%s}' % QColor(222, 222, 222).name())  # 设置窗口背景色self.setWindowOpacity(0.95)  # 设置整个计算器窗口的透明度ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")  # 任务栏图标self.setWindowFlags(Qt.FramelessWindowHint)self.show()self.set_input()  # 输入账号和输入密码的设置# 将信号连接到对应槽函数self.login_button.clicked.connect(self.username_password)self.forget.clicked.connect(self.forget_password)self.login_close.clicked.connect(QCoreApplication.instance().quit)# 输入账号和输入密码的设置def set_input(self):self.input_username.setPlaceholderText("请输入账号")  # 灰色的占位符self.input_password.setPlaceholderText("请输入密码")  # 灰色的占位符self.input_username.setContextMenuPolicy(Qt.NoContextMenu)  # 禁止复制粘贴self.input_password.setContextMenuPolicy(Qt.NoContextMenu)  # 禁止复制粘贴self.input_password.setEchoMode(QLineEdit.Password)  # 输入时呈现圆点,不显示密码# 检查用户名与密码是否匹配def username_password(self):if load(self.input_username.text(), self.input_password.text()):self.hide()self.signal.emit()  # 发射信号else:QMessageBox.warning(self, "错误", "账号或密码错误!")self.input_password.setText('')pass# 忘记密码按钮触发的信号def forget_password(self):self.hide()self.forget_signal.emit()  # 发射忘记密码信号# 键盘登录def keyPressEvent(self, event):QWidget.keyPressEvent(self, event)key = event.key()if key == Qt.Key_Enter:self.username_password()

三、忘记密码窗口(ForgetWindow.py)

  忘记密码窗口负责校验密保问题,判断用户是否拥有修改密码权限。

在这里插入代码片from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import ctypes
import re
from PyQt5.QtWidgets import QMessageBox, QWidget, QLineEdit
from Functions import SecurityQuestion, ResetPassword
from SecurityQuestion_UI import Ui_SecurityQuestionWindow
from Reset_UI import Ui_ResetWindowglobal username_changingclass SecurityQuestionWindow(QtWidgets.QMainWindow, Ui_SecurityQuestionWindow):signal = pyqtSignal()back_signal = pyqtSignal()def __init__(self):super().__init__()self.setupUi(self)self.setWindowTitle('忘记密码')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")  # 任务栏图标self.setWindowFlags(Qt.FramelessWindowHint)# 将信号连接到对应槽函数self.confirm_button.clicked.connect(self.security_question)self.back_button.clicked.connect(self.back_to_login)self.close_button.clicked.connect(QCoreApplication.instance().quit)# 检查用户名与密保是否匹配def security_question(self):if SecurityQuestion(self.input_username.text(), self.input_security.text()):global username_changingusername_changing = self.input_username.text()self.input_username.setText('')self.input_security.setText('')self.hide()self.signal.emit()  # 发射信号else:QMessageBox.warning(self, "错误", "密保错误!")self.input_security.setText('')# 键盘确认def keyPressEvent(self, event):QWidget.keyPressEvent(self, event)key = event.key()if key == Qt.Key_Enter:self.security_question()def back_to_login(self):self.hide()self.back_signal.emit()  # 触发返回登陆界面的信号class ResetWindow(QtWidgets.QMainWindow, Ui_ResetWindow):signal = pyqtSignal()back_signal = pyqtSignal()def __init__(self):super().__init__()self.setupUi(self)self.setWindowTitle('重置密码')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标# self.setStyleSheet('QWidget{background-color:%s}' % QColor(222, 222, 222).name())  # 设置窗口背景色ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")  # 任务栏图标self.setWindowFlags(Qt.FramelessWindowHint)self.set_input()  # 输入密码的设置# 将信号连接到对应槽函数self.submit_button.clicked.connect(self.Reset)self.back_button.clicked.connect(self.back_to_login)self.close_button.clicked.connect(QCoreApplication.instance().quit)def set_input(self):self.input_pass1.setContextMenuPolicy(Qt.NoContextMenu)  # 禁止复制粘贴self.input_pass2.setContextMenuPolicy(Qt.NoContextMenu)  # 禁止复制粘贴self.input_pass1.setEchoMode(QLineEdit.Password)  # 输入时呈现圆点,不显示密码self.input_pass2.setEchoMode(QLineEdit.Password)  # 输入时呈现圆点,不显示密码# 检查用户名与密保是否匹配def Reset(self):regx = re.compile(r"^[a-zA-Z]\w{5,14}")global username_changingif username_changing != '' and self.input_pass1.text() == self.input_pass2.text() and regx.match(self.input_pass1.text()) is not None:if regx.match(self.input_pass1.text()).group() == self.input_pass1.text():ResetPassword(username_changing, self.input_pass1.text())QMessageBox.information(self, "信息", "修改密码成功!")self.input_pass1.setText('')self.input_pass2.setText('')self.hide()self.signal.emit()  # 发射信号else:QMessageBox.warning(self, "警告", "请输入符合条件的密码!")self.input_pass1.setText('')self.input_pass2.setText('')else:if self.input_pass1.text() != self.input_pass2.text():QMessageBox.warning(self, "警告", "两次输入的密码不一致,请重新输入!")else:QMessageBox.warning(self, "警告", "请输入符合条件的密码!")self.input_pass1.setText('')self.input_pass2.setText('')# 键盘确认def keyPressEvent(self, event):QWidget.keyPressEvent(self, event)key = event.key()if key == Qt.Key_Enter:self.Reset()def back_to_login(self):self.hide()self.back_signal.emit()  # 触发返回登陆界面的信号

四、主窗口(MainWindow.py)(重点)

  这部分是我重点负责的部分,我将比较详细的解释代码。

1. 成员变量
# 在PyQt5里创建的是QMainWindow,不是Widget,需要注意的是,创建的元素一定要调用正确。
class MainWindow(QMainWindow, Ui_MainWindow):insert_signal = pyqtSignal()    # 定义插入信号batch_signal = pyqtSignal()     # 定义批量插入信号query_flag = 0      # 查询标记check_list = []     # 确认列表delete_f = -1       # 批量删除选定初始行delete_t = -1       # 批量删除选定末尾行
2. 构造函数

  注释写的比较明了,就不过多赘述。

    def __init__(self):# 初始化窗口super().__init__()self.setupUi(self)self.setWindowTitle('校园一卡通管理系统')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标self.setWindowOpacity(1)  # 设置整个窗口的透明度为不透明# 初始化编辑框self.lineEdit_id.setText("")self.lineEdit_name.setText("")self.lineEdit_phonenumber.setText("")# 初始化下拉框self.comboBox_sex.addItems(["", "男", "女"])self.comboBox_college.addItems(["", "计算机学院", "机械学院", "外国语学院"])self.comboBox_major.addItems(["", "物联网工程", "计算机科学与技术", "软件工程", "通信工程", "信息安全"])self.comboBox_sex_2.addItems(["", "充值", "饮食", "电费", "水费", "车费"])# 初始化标记self.query_flag = 0self.check_list = []self.delete_f = -1self.delete_t = -1# 信号和槽函数绑定# 栏目1(学生基本信息)self.pushButton_query.clicked.connect(self.query)  # 为按钮添加点击事件self.comboBox_college.activated.connect(self.update_ComboBox)   # 如果下拉框被激活就更新子下拉框self.pushButton_insert.clicked.connect(self.insert_button_signal)  # 弹出插入窗口self.pushButton_delete.clicked.connect(self.deleteConfirm)  # 删除操作self.tableWidget.itemChanged.connect(self.update_tableWidget)  # 查找操作self.tableWidget.cellPressed.connect(self.update_flag)  # 更新查找标记self.tableWidget.itemSelectionChanged.connect(self.update_selected) # 更新选择区域self.pushButton_batch.clicked.connect(self.batch_button_signal) # 批量插入# 栏目2(交易记录)self.pushButton_query_2.clicked.connect(self.upadate_tableWidget2)  # 查记录# 栏目3(充值界面按钮绑定)self.top_up_button.clicked.connect(self.top_up) # 绑定充值
3. 更新选择区域

  当表格中选中区域发生改变时,更新当前选择区域。

    # 更新选择区域def update_selected(self):list = self.tableWidget.selectedRanges()for temp in list:self.delete_f = temp.topRow()self.delete_t = temp.bottomRow()
4. 便捷修改记录

  获取当前选中行列,更新当前行列中的数据。

    # 修改表信息def update_tableWidget(self):# print(self.tableWidget.selectedItems()==None)# print("x: " + str(self.tableWidget.selectedIndexes()[0].row()) + ",  y: " + str(self.tableWidget.selectedIndexes()[0].column()))# print("请求修改信息")if self.query_flag == 1:returni = self.tableWidget.currentIndex().row()j = self.tableWidget.currentIndex().column()lable = ['学号', '姓名', '性别', '学院', '专业', '手机号', '余额']# print(self.tableWidget.item(i,0).text(),lable[j],self.tableWidget.item(i,j).text())DataUpdate(self.tableWidget.item(i, 0).text(), lable[j], self.tableWidget.item(i, j).text())
5. 更新标记 & 发射信号

  当表格中有元素被按下就更新查询标记,防止查询bug。另外两个信号是用来弹出窗口的。

# 更新标志def update_flag(self):# print("flag")self.query_flag = 0# 批量插入按钮发射信号def batch_button_signal(self):self.batch_signal.emit()  # 发射信号# 插入按钮发射信号def insert_button_signal(self):self.insert_signal.emit()  # 发射信号
6. 单个删除 & 批量删除

  单个选择删除和批量删除二者通过当前选择行列来判断是哪一种。同时删除之前会弹出消息框来确认是否删除。批量删除的实现是通过检查查看复选框的选择状态来实现批量删除的。

    # 批量删除def delete2(self):if self.delete_f == -1 and self.delete_t == -1:# QMessageBox.warning(self, "失败", "请框选需要删除的记录!")return Falsefor i in range(self.delete_f,self.delete_t + 1):DeleteData(str(self.tableWidget.item(i, 0).text()))self.query()QMessageBox.information(self, "信息", "删除记录成功!")self.delete_t = -1self.delete_f = -1return True# 删除确认def deleteConfirm(self):message_box = QMessageBox()message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)message_box.setWindowTitle("提示")message_box.setText("确认删除?")message_box.setWindowIcon(QIcon('logo.png'))yes = message_box.button(QMessageBox.Yes)yes.clicked.connect(self.delete)  # 点击此按钮则退出程序message_box.exec()# 删除按钮发射信号def delete(self):if self.delete2():returnflag = 0for i in range(0, self.tableWidget.rowCount()):if self.check_list[i].checkState() == 2:flag = 1DeleteData(str(self.tableWidget.item(i, 0).text()))if flag == 1:self.query()QMessageBox.information(self, "提示", "删除记录成功!")self.delete_t = -1self.delete_f = -1else:QMessageBox.critical(self, "失败", "请勾选需要删除的记录!")
7. 下拉框元素更新
    # 下拉框增加元素def update_ComboBox(self):coll = self.comboBox_college.currentText()self.comboBox_major.clear()if coll == "计算机学院":self.comboBox_major.addItems(["物联网工程", "计算机科学与技术", "软件工程", "通信工程", "信息安全"])elif coll == "机械学院":self.comboBox_major.addItems(["机械电子工程", "测控技术与仪器", "机械设计制造", "工业设计"])elif coll == "外国语学院":self.comboBox_major.addItems(["英语", "俄语", "日语", "法语", "西班牙语"])
8. 模糊查找

  通过获取编辑框和下拉框的数据来进行查找,通过输入的字段来改变sql语句进行模糊查询。

    # 模糊查找def query(self):self.query_flag = 1id = self.lineEdit_id.text()name = self.lineEdit_name.text()sex = self.comboBox_sex.currentText()coll = self.comboBox_college.currentText()major = self.comboBox_major.currentText()number = self.lineEdit_phonenumber.text()result = informationInput(id, name, sex, coll, major, number)self.check_list.clear()for i in range(0, result.__len__()):# 下面六行用于生成居中的checkbox,不知道有没有别的好方法ck = QCheckBox()self.check_list.append(ck)# 调用数据库self.tableWidget.setRowCount(result.__len__())self.tableWidget.setColumnCount(8)self.tableWidget.setHorizontalHeaderLabels(['学号', '姓名', '性别', '学院', '专业', '手机号', '余额', '选择'])self.tableWidget.setColumnWidth(0, 200)self.tableWidget.setColumnWidth(1, 100)self.tableWidget.setColumnWidth(2, 50)self.tableWidget.setColumnWidth(3, 160)self.tableWidget.setColumnWidth(4, 160)self.tableWidget.setColumnWidth(5, 150)self.tableWidget.setColumnWidth(6, 120)self.tableWidget.setColumnWidth(7, 87)for i in range(0, self.tableWidget.rowCount()):self.tableWidget.setRowHeight(i, 44)lable1 = ['学号', '姓名', '性别', '学院', '专业', '手机号', '余额', '选择']for i in range(result.__len__()):temp = result[i]for j in range(0, lable1.__len__()):if j < 7:if temp[lable1[j]] is not None:self.tableWidget.setItem(i, j, QTableWidgetItem(str(temp[lable1[j]])))else:self.tableWidget.setItem(i, j, QTableWidgetItem(" "))else:h = QHBoxLayout()h.setAlignment(Qt.AlignCenter)h.addWidget(self.check_list[i])w = QWidget()w.setLayout(h)self.tableWidget.setCellWidget(i, j, w)
9. 更新交易记录

  根据输入字段模糊查找交易记录。

    # 更新交易记录def upadate_tableWidget2(self):id2 = self.lineEdit_id_2.text()name2 = self.lineEdit_name_2.text()type2 = self.comboBox_sex_2.currentText()result = TransactionRecords(id2, name2, type2)# 调用数据库lable1 = ['学号', '姓名', '消费类型', '消费时间', '金额变动', '余额']self.tableWidget_2.setRowCount(result.__len__())self.tableWidget_2.setColumnCount(6)self.tableWidget_2.setHorizontalHeaderLabels(lable1)self.tableWidget_2.setColumnWidth(0, 200)self.tableWidget_2.setColumnWidth(1, 150)self.tableWidget_2.setColumnWidth(2, 100)self.tableWidget_2.setColumnWidth(3, 300)self.tableWidget_2.setColumnWidth(4, 138)self.tableWidget_2.setColumnWidth(5, 138)for i in range(0, self.tableWidget_2.rowCount()):self.tableWidget_2.setRowHeight(i, 45)for i in range(result.__len__()):temp = result[i]for j in range(0, lable1.__len__()):if temp[j] is not None:if j == 4:money = str(temp[j])if money[0] != '-':money = "+ " + moneyelse:money = "- " + money[1:]self.tableWidget_2.setItem(i, 4, QTableWidgetItem(money))else:self.tableWidget_2.setItem(i, j, QTableWidgetItem(str(temp[j])))else:self.tableWidget_2.setItem(i, j, QTableWidgetItem(" "))
10. 充值

  通过学号和充值金额进行更新数据。

    # 充值def top_up(self):username = self.top_up_id.text()money = self.top_up_money.text()result = Recharge(money, username)if result == 0:QMessageBox.warning(self, "错误", "请输入有效学号!")self.top_up_id.setText('')elif result == 1:QMessageBox.warning(self, "错误", "请输入正确金额!")self.top_up_money.setText('')else:QMessageBox.information(self, "成功", "充值成功!")self.top_up_id.setText('')self.top_up_money.setText('')

五、单条插入窗口(InsertWindow.py)

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QIcon
from PyQt5.QtWidgets import *
from Insert_UI import Ui_InsertWindow
from Functions import *class InsertWindow(QMainWindow, Ui_InsertWindow):inserted_signal = pyqtSignal()def __init__(self):super().__init__()self.setupUi(self)self.setWindowTitle('校园一卡通管理系统')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标# self.setWindowIcon(QIcon('1.jpg'))  # 设置窗口图标# self.setStyleSheet('QWidget{background-color:%s}' % QColor(222, 222, 222).name())  # 设置窗口背景色self.setWindowOpacity(1)  # 设置整个计算器窗口的透明度# ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")  # 任务栏图标self.comboBox_sex.addItems([" ", "男", "女"])self.comboBox_college.addItems([" ", "计算机学院", "机械学院", "外国语学院"])self.comboBox_major.addItems([" ", "物联网工程", "计算机科学与技术", "软件工程", "通信工程", "信息安全"])# self.show()# 按钮绑定self.pushButton_insert.clicked.connect(self.insert)  # 插入事件self.comboBox_college.activated.connect(self.update_ComboBox)# 下拉框增加元素def update_ComboBox(self):coll = self.comboBox_college.currentText()self.comboBox_major.clear()if coll == "计算机学院":self.comboBox_major.addItems(["物联网工程", "计算机科学与技术", "软件工程", "通信工程", "信息安全"])elif coll == "机械学院":self.comboBox_major.addItems(["机械电子工程", "测控技术与仪器", "机械设计制造", "工业设计"])elif coll == "外国语学院":self.comboBox_major.addItems(["英语", "俄语", "日语", "法语", "西班牙语"])def insert(self):# 数据库交互id = self.lineEdit_id.text()name = self.lineEdit_name.text()sex = self.comboBox_sex.currentText()coll = self.comboBox_college.currentText()major = self.comboBox_major.currentText()number = self.lineEdit_phonenumber.text()Imformation(id, name, sex, coll, major, number)self.inserted_signal.emit()QMessageBox.information(self, "成功", "插入记录成功!")pass

六、批量导入窗口(BatchInsertedWindow.py)

import osfrom PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import ctypes
import time
from PyQt5.QtWidgets import QLineEdit, QMessageBox, QWidgetfrom BatchInserted_UI import Ui_BatchInsertedWindowclass BatchInsertedWindow(QtWidgets.QMainWindow, Ui_BatchInsertedWindow):step = 0first = 0last = 0number = 1def __init__(self):super().__init__()self.setupUi(self)self.setWindowTitle('校园一卡通管理系统')  # 设置窗口标题self.setWindowIcon(QIcon('logo.png'))  # 设置窗口图标ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")  # 任务栏图标# 将信号连接到对应槽函数self.batch_insert_button.clicked.connect(self.BatchInsert)# self.batch_insert_button.clicked.connect(self.timerEvent)self.timer = QBasicTimerself.pbar.setValue(self.step)# 键盘登录def keyPressEvent(self, event):QWidget.keyPressEvent(self, event)key = event.key()if key == Qt.Key_Enter:self.BatchInsert()def BatchInsert(self):path = self.insert_path.text()self.first = self.lineEdit.text()self.last = self.lineEdit_2.text()self.StudentInformation(path, self.first, self.last)def StudentInformation(self, path, start, last):import pymysqlfrom openpyxl import load_workbookfrom datetime import date, datetimedb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()if path == "":path = ".//student.xlsx"if os.path.exists(path):workbook = load_workbook(filename=path)sheet1 = workbook["sheet1"]if start == "":start = 1if last == "":last = 1start = int(start)last = int(last)self.step = 0self.first = startself.last = lastfrom builtins import strlist1 = []# from builtins import rangefor q in range(start, last + 1):list1.append([])# print(q)for row in sheet1.iter_rows(min_row=q, max_row=q):# print(row)for cell in row:# from builtins import strstring = str(cell.value)# print(string)# print(string)list1[q - start].append(string)# print(list1)cnt = 0for i in range(0, len(list1)):date = list1[i]# print(i, date)# print(date)str1 = ""self.number = i + 1for j in range(6):str1 += "'" + date[j] + "',"str1 = str1[:-1]sql_str = "INSERT INTO 学生基本信息(学号, 姓名, 性别, 学院, 专业, 手机号, 余额) VALUES(%s,%s)" % (str1, int(date[6]))try:# 执行sql语句db.ping(reconnect=True)cursor.execute(sql_str)db.commit()cnt += 1except Exception as e:# 如果发生错误则回滚print("修改失败!")print(e)db.rollback()# 关闭数据库连接db.close()# print(len(list1))self.step = self.number / (self.last + 1 - self.first) * 100self.pbar.setValue(self.step)if self.step == 100.0:time.sleep(0.3)text = '成功插入' + str(cnt) + '条记录!'QMessageBox.warning(self, "成功", text)self.step = 0self.pbar.setValue(self.step)else:QMessageBox.warning(self, "错误", "请输入正确路径!")

七、与数据库交互的各种方法(Functions.py)

  与数据库进行增删改查等操作的各种方法。

from datetime import datetime
from multiprocessing import connectionCno = '0'  # 用于最后的注销# 注册账号密码
# 对应参数分别是学号,密码,密保
def register(studentNumber, password, SecretGuard):import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()ch = "select 学号 from 学生基本信息 where 学号='%s'" % studentNumbercursor.execute(ch)ch1 = cursor.fetchone()if ch1 == None:print("学号输入错误")else:sql = """INSERT INTO 注册(学号,密码,密保)VALUES ('%s', '%s', '%s')""" % (studentNumber, password, SecretGuard)try:# 执行sql语句cursor.execute(sql)# 提交到数据库执行db.commit()except:# 如果发生错误则回滚db.rollback()# 关闭数据库连接db.close()else:print("注册成功!")return# 登录
# 需要对应的变量来存放登录的账号
def load(studentNumber, password):global Cnoimport pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)cur = connection.cursor()# pattern = re.compile()sqlDL = "select 学号  from 注册 where 注册.学号='%s' and 注册.密码='%s'" % (studentNumber, password)cur.execute(sqlDL)jilu = cur.fetchone()  # 注册表中没有对应账号和密码if jilu == None:return Falseelif jilu != None:Cno = studentNumberreturn True# 信息的录入
# 对应参数分别是 学号 性别 姓名 学院 专业 手机号 余额
def Imformation(studentNumber, name, gender, College, major, mobileNumber):import pymysql# 打开数据库连接db = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标cursor = db.cursor()money = 100lable = [studentNumber, name, gender, College, major, mobileNumber]lable1 = ['学号', '姓名', '性别', '学院', '专业', '手机号']str = ''  # 初始化为空串str1 = ''flag = 0for i in range(4, 6):# print(i)if lable[i] != '':str1 += lable1[i] + ","flag = 1str += "'" + lable[i] + "',"str = str[:-1]str1 = str1[:-1]# print(studentNumber)# # SQL 插入语句if flag == 0:sql = "INSERT INTO 学生基本信息(学号,姓名,性别,学院,余额) VALUES('%s','%s','%s','%s',%s)" % (studentNumber, name, gender, College, money)else:sql = "INSERT INTO 学生基本信息(学号,姓名,性别,学院,%s,余额) VALUES ('%s','%s','%s','%s',%s, %s)" % (str1, studentNumber, name, gender, College, str, money)try:# 执行sql语句print(sql)cursor.execute(sql)# 提交到数据库执行db.commit()except:# 如果发生错误则回滚print("信息录入错误")db.rollback()# 关闭数据库连接db.close()else:print('信息录入成功')return# 对应参数是 属性和具体的值   比如性别,男
def Check(fun, natural):import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)cur = connection.cursor()if fun == '性别':sqlJiaoYi = "select * from 交易记录 where 性别='%s'" % (natural)elif fun == '学号':sqlJiaoYi = "select * from 交易记录 where 学号='%s'" % (natural)elif fun == '消费类型':sqlJiaoYi = "select * from 交易记录 where 消费类型='%s'" % (natural)elif fun == '1':sqlJiaoYi = "select * from 交易记录"cur.execute(sqlJiaoYi)result = cur.fetchall()for data in result:print(data)cur.close()connection.close()# Check('性别', '女')
# 充值校园卡   要改
# 对应参数是 钱数 学号 时间
def Recharge(money, nameNumber):import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标cursor = db.cursor()time = datetime.now()ch = "select 学号 from 学生基本信息 where 学号='%s'" % (nameNumber)cursor.execute(ch)  # 加载到数据库中ch1 = cursor.fetchone()  # 将数据拿出来if ch1 is None:return 0else:sql1 = "select 学号,余额 from 学生基本信息 where 学号='%s'" % (nameNumber)cursor.execute(sql1)ch3 = cursor.fetchone()print(ch3)sql = "update 学生基本信息 set 余额=余额+%s where 学号='%s'" % (money, nameNumber)sql3 = "INSERT INTO 交易记录(学号,消费类型,金额变动,消费时间,余额) VALUES ('%s','充值',%s,'%s',%s)" % (ch3[0], money, time, ch3[1] + float(money))print(sql)print(sql3)try:# 执行sql语句cursor.execute(sql)# 提交到数据库执行db.commit()cursor.execute(sql3)db.commit()return 2except:# 如果发生错误则回滚db.rollback()# 关闭数据库连接db.close()return 1#  修改信息
# 对应参数是学号
def Exchange(name):import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)cur = connection.cursor()secretGuard = input("请输入密保:")sqlXH = "select 密保 from 注册 where 注册.学号='%s'" % (name)cur.execute(sqlXH)jilu = cur.fetchone()# for data in jilu:if jilu == {'密保': secretGuard}:NewpPassword = input("请输入新密码:")sqlNewPassword = "update 注册 set 密码='%s' where 学号='%s'" % (NewpPassword, name)print("修改成功")elif jilu != {'密码': secretGuard}:print("密保错误")Exchange(name)cur.close()connection.close()# 基本信息表的输出
# 对应参数是要输出的表 比如要输出学生基本信息  str=学生基本信息
def inputInformation(str):import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)try:cursor = connection.cursor()sql = "select * from %s" % (str)cursor.execute(sql)result = cursor.fetchall()# 信息的输出for data in result:print(data)except Exception as e:print("信息输入错误")# 提示错误信息# print(e)cursor.close()connection.close()return# str = input("请输入所要输出的表的名字:")
# inputInformation(str)# 注销账号
def logOut():import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()sql = "delete from 学生基本信息 where 学号='%s'" % Cnosql1 = "delete from 注册 where 学号='%s'" % Cnosql2 = "delete from 交易记录 where 学号='%s'" % Cnotry:# 执行sql语句cursor.execute(sql1)# 提交到数据库执行db.commit()cursor.execute(sql2)db.commit()cursor.execute(sql)db.commit()except:# 如果发生错误则回滚print("注销失败!")db.rollback()# 关闭数据库连接db.close()else:print("注销成功!")# 学生基本信息查询
def informationInput(studentNumber, name, gender, College, major, mobileNumber):lable = [studentNumber, name, gender, College, major, mobileNumber]lable1 = ['学号', '姓名', '性别', '学院', '专业', '手机号']str = ""  # 初始化为空串flag = 0for i in range(6):if lable[i] != '':flag = 1# str += (lable1[i] + "='" + lable[i] + "' and ")str += (lable1[i] + " LIKE '%" + lable[i] + "%' and ")str = str[:-5]# print(str)import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)try:cursor = connection.cursor()if flag == 0:sql = "select * from 学生基本信息"else:sql = "select * from 学生基本信息 where %s" % strcursor.execute(sql)result = cursor.fetchall()# 信息的输出return resultexcept Exception as e:print("信息输入错误")# 提示错误信息print(e)cursor.close()connection.close()def DataUpdate(studentNumber, attribute, val):import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()sql = "update 学生基本信息 set %s='%s' where 学号='%s'" % (attribute, val, studentNumber)print(sql)try:# 执行sql语句cursor.execute(sql)# 提交到数据库执行db.commit()except:# 如果发生错误则回滚print("修改失败!")db.rollback()# 关闭数据库连接db.close()else:print("修改成功!")def DeleteData(studentNumber):import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()# print(studentNumber)sql = "DELETE FROM 学生基本信息 WHERE 学号='%s'" % (studentNumber)sql1 = "DELETE FROM 交易记录 WHERE 学号='%s'" % (studentNumber)try:# 执行sql语句cursor.execute(sql1)# 提交到数据库执行db.commit()cursor.execute(sql)# 提交到数据库执行db.commit()except:# 如果发生错误则回滚print("删除信息失败!")#         db.rollback()#         # 关闭数据库连接db.close()else:print("删除成功!")# 交易记录输出
def TransactionRecords(studentNumber, name, ConsumptionType):lable = [studentNumber, name, ConsumptionType]lable1 = ['学号', '姓名', '消费类型']str = ""  # 初始化为空串flag = 0for i in range(3):if lable[i] != "":flag = 1if i == 0:str += "学生基本信息." + lable1[i] + " LIKE '%" + lable[i] + "%' and "elif i == 1:str += "学生基本信息." + lable1[i] + " LIKE '%" + lable[i] + "%' and "elif i == 2:str += lable1[i] + " LIKE '%" + lable[i] + "%' and "if str.__len__()>5:str = str[:-5]import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon')cur = connection.cursor()if flag == 0:sql = "select 学生基本信息.学号,学生基本信息.姓名,消费类型,消费时间,金额变动,交易记录.余额 from 学生基本信息,交易记录 where 学生基本信息.学号=交易记录.学号"else:sql = "select 学生基本信息.学号,学生基本信息.姓名,消费类型,消费时间,金额变动,交易记录.余额 from 交易记录,学生基本信息 where 学生基本信息.学号=交易记录.学号 and %s" % str# print(sql)cur.execute(sql)result = cur.fetchall()# print(result)# for data in result:#     print(data)# 更改字段list = []for i in range(result.__len__()):temp = result[i]list.append([])for j in range(0, 6):list[i].append(temp[j])return listcur.close()connection.close()# 检查密保问题
def SecurityQuestion(name, secretGuard):import pymysql.cursorsconnection = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='onecartoon',charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)cur = connection.cursor()sqlXH = "select 密保 from 注册 where 注册.学号='%s'" % namecur.execute(sqlXH)jilu = cur.fetchone()# for data in jilu:cur.close()connection.close()if jilu == {'密保': secretGuard}:return Trueelse:return False# 重置密码
def ResetPassword(name, new_password):import pymysqldb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标cursor = db.cursor()sqlNewPassword = "update 注册 set 密码='%s' where 学号='%s'" % (new_password, name)cursor.execute(sqlNewPassword)  # 提交到数据库执行db.commit()# 关闭数据库连接db.close()def StudentInformation(path, start, last):import pymysqlfrom openpyxl import load_workbookfrom datetime import date, datetimedb = pymysql.connect("localhost", "root", "123456", "onecartoon")# 使用cursor()方法获取操作游标# 使用cursor()方法获取操作游标cursor = db.cursor()print("666")if path == "":path = "student.xlsx"workbook = load_workbook(filename=".\\" + path)# print(workbook.sheetnames)sheet1 = workbook["sheet1"]print("999")if start == "":start = 1if last == "":last = 1start = int(start)last = int(last)print("start:" + str(start) + ",  end:" + str(last))list1 = []# from builtins import rangefor q in range(start, last+1):list1.append([])# print(q)for row in sheet1.iter_rows(min_row=q, max_row=q):# print(row)for cell in row:# from builtins import strstring = str(cell.value)# print(string)# print(string)list1[q - start].append(string)print(list1)for i in range(0, len(list1)):date = list1[i]# print(i, date)# print(date)str1 = ""for j in range(6):str1 += "'" + date[j] + "',"str1 = str1[:-1]sql_str = "INSERT INTO 学生基本信息(学号, 姓名, 性别, 学院, 专业, 手机号, 余额) VALUES(%s,%s)" % (str1, int(date[6]))print(sql_str)try:# 执行sql语句db.ping(reconnect=True)cursor.execute(sql_str)db.commit()except Exception as e:# 如果发生错误则回滚print("修改失败!")print(e)db.rollback()# 关闭数据库连接db.close()

———2020.12.27(罗涵)

THE END

计算机软件实习项目四 —— 校园一卡通管理系统 (代码实现) 12-27相关推荐

  1. 软件实习项目4——校园一卡通管理系统(成品展示)

    软件实习项目4--校园一卡通管理系统(成品展示) 成品展示 1.登录界面 2.密保验证 3.重置密码 4.主界面 视频演示 成品展示 1.登录界面 2.密保验证 3.重置密码 4.主界面 1)学生基本 ...

  2. SSM毕设项目高校校园一卡通管理系统hwi15(java+VUE+Mybatis+Maven+Mysql)

    SSM毕设项目高校校园一卡通管理系统hwi15(java+VUE+Mybatis+Maven+Mysql) 项目运行 环境配置: Jdk1.8 + Tomcat8.5 + Mysql + HBuild ...

  3. 软件实习实验四 校园一卡通数据库管理系统的开发

    2020-12-24 源代码在Github:https://github.com/llq-007/Campus-card-database-management-system 文章目录 项目概述及设计 ...

  4. 计算机软件实习项目三 —— 超级玛丽闯迷宫 (代码实现) 12-21

    代码实现(超级玛丽闯迷宫)   上一篇博客对这个游戏的整体框架以及算法的流程进行了比较详细的设计及分析:对必要的类和类的成员变量.类的方法进行了声明以及声明.这一篇博客主要来呈现相关代码. 目录 代码 ...

  5. 计算机软件实习项目二 —— 贪吃蛇游戏 (代码实现) 12-16

    代码实现   不得不说python真是太香了,我感觉写起来比C++快,而且代码量更少,还有非常多十分方便的方法可以使用.在pycharm里有非常多的快捷键十分的方便,相较项目使用的visual stu ...

  6. Java毕设项目校园一卡通管理系统计算机(附源码+系统+数据库+LW)

    Java毕设项目校园一卡通管理系统计算机(附源码+系统+数据库+LW) 项目运行 环境配置: Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ E ...

  7. JAVA毕设项目西安财经大学校园一卡通管理系统(java+VUE+Mybatis+Maven+Mysql)

    JAVA毕设项目西安财经大学校园一卡通管理系统(java+VUE+Mybatis+Maven+Mysql) 项目运行 环境配置: Jdk1.8 + Tomcat8.5 + Mysql + HBuild ...

  8. 基于JAVA校园一卡通管理系统计算机毕业设计源码+系统+数据库+lw文档+部署

    基于JAVA校园一卡通管理系统计算机毕业设计源码+系统+数据库+lw文档+部署 基于JAVA校园一卡通管理系统计算机毕业设计源码+系统+数据库+lw文档+部署 本源码技术栈: 项目架构:B/S架构 开 ...

  9. java毕业设计西安财经大学校园一卡通管理系统源码+lw文档+mybatis+系统+mysql数据库+调试

    java毕业设计西安财经大学校园一卡通管理系统源码+lw文档+mybatis+系统+mysql数据库+调试 java毕业设计西安财经大学校园一卡通管理系统源码+lw文档+mybatis+系统+mysq ...

  10. java计算机毕业设计校园一卡通管理系统源码+mysql数据库+lw文档+系统+调试部署

    java计算机毕业设计校园一卡通管理系统源码+mysql数据库+lw文档+系统+调试部署 java计算机毕业设计校园一卡通管理系统源码+mysql数据库+lw文档+系统+调试部署 本源码技术栈: 项目 ...

最新文章

  1. 数据挖掘-matplotlib、numpy、pandas(二)
  2. C++从零实现神经网络(收藏版:两万字长文)
  3. 通过对比对象掩码建议的无监督语义分割
  4. LeetCode.917-只反转字母(Reverse Only Letters)
  5. [原]win32 rundll32 应用列表
  6. python内存池机制_python的内存管理机制
  7. 对Html里的title属性的换行
  8. diy 单片机 自动浇花_造个自动浇花装置(完)
  9. Entity Framework 学习高级篇2—改善EF代码的方法(下)(转)
  10. linux 下svn安装
  11. Jmeter压力测试实例
  12. secoclient免积分下载
  13. 百度地图API基础操作--导航篇
  14. 1688-cat_get - 获得1688商品分类
  15. 导出 MySQL 数据库表结构设计文档
  16. kettle-新建资源库connect资源库灰色解决
  17. 使用Eclipse Memory Analyzer分析Tomcat内存溢出
  18. 清默网络——我的CCIE考试经验与心得(2)
  19. FCPX插件:分屏转场插件Stupid Raisins Shape Pop
  20. 一些恶搞的bat小脚本

热门文章

  1. 推荐linux输入法,linux中文输入法 【搞定技巧】
  2. java如何从服务器上删除文件,java从服务器删除文件
  3. 我的世界java版刷铁机_我的世界:教你建造新版本中最简单的刷铁机,效率高人人学的会...
  4. 深入针式PKM应用系列
  5. Windows -- ThinkPad E470 win10-64bit显示问题和声音播放问题
  6. setuna截图软件怎么用_苹果手机笔记怎么做?用哪款笔记软件好
  7. 工业非标设备远程运维方案
  8. Eclipse反编译jad插件安装
  9. SQL 数据定义语句(DDL)
  10. 图论画图工具 Graph Editor