基于MySQL有用戶管理的音樂播放器

基于MySQL的音樂器

  • 帶有用戶登錄功能
  • 驗證用戶身份,用戶注冊等操作
  • 還有用戶音樂列表,以及增刪查改操作

INSERT into users(username,passwd,phone_number,created_time,role) VALUES(‘張三’,‘123456’,‘123’,‘2025-3-11’,‘1’)

三張表,users表,存放用戶信息

musiclibrary表存放音樂信息

user_favorites表放用戶id和音樂id,就是用戶的個人喜好。所有用戶的個人喜好都在這個表里面

關于音樂下載的,可以看我以前的爬蟲文章,復制源代碼,運行就是一個音樂下載器了。再配合這個音樂播放器,非常好用,安利一下。鏈接:
https://blog.csdn.net/FZ51111/article/details/143540349?spm=1011.2415.3001.5331

  • 第一次,手搓這個音樂播放器,有很多可以優化的地方
"""
基于MySQL的音樂器
有用戶登錄功能
還要用戶注冊
用戶個人的音樂列表,還有對應的增刪查
"""
import re
import threadingimport pygame
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QStackedWidget, QVBoxLayout, QFileDialog
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
import pymysql
from datetime import datetime
from playsound import playsoundclass Ui_denglu(QWidget):def setupUi(self, denglu):denglu.setObjectName("denglu")denglu.resize(420, 281)font = QtGui.QFont()font.setBold(True)font.setWeight(75)denglu.setFont(font)self.verticalLayout = QtWidgets.QVBoxLayout(denglu)self.verticalLayout.setObjectName("verticalLayout")self.horizontalLayout = QtWidgets.QHBoxLayout()self.horizontalLayout.setObjectName("horizontalLayout")self.label = QtWidgets.QLabel(denglu)self.label.setObjectName("label")self.horizontalLayout.addWidget(self.label)self.lineEdit = QtWidgets.QLineEdit(denglu)self.lineEdit.setObjectName("lineEdit")self.horizontalLayout.addWidget(self.lineEdit)self.verticalLayout.addLayout(self.horizontalLayout)self.horizontalLayout_2 = QtWidgets.QHBoxLayout()self.horizontalLayout_2.setObjectName("horizontalLayout_2")self.label_2 = QtWidgets.QLabel(denglu)self.label_2.setObjectName("label_2")self.horizontalLayout_2.addWidget(self.label_2)self.lineEdit_2 = QtWidgets.QLineEdit(denglu)self.lineEdit_2.setObjectName("lineEdit_2")self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)self.horizontalLayout_2.addWidget(self.lineEdit_2)self.verticalLayout.addLayout(self.horizontalLayout_2)self.horizontalLayout_3 = QtWidgets.QHBoxLayout()self.horizontalLayout_3.setObjectName("horizontalLayout_3")spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_3.addItem(spacerItem)self.pushButton = QtWidgets.QPushButton(denglu)self.pushButton.setObjectName("pushButton")self.horizontalLayout_3.addWidget(self.pushButton)spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_3.addItem(spacerItem1)self.verticalLayout.addLayout(self.horizontalLayout_3)self.horizontalLayout_4 = QtWidgets.QHBoxLayout()self.horizontalLayout_4.setObjectName("horizontalLayout_4")self.label_3 = QtWidgets.QLabel(denglu)self.label_3.setStyleSheet("color:\'#EEB422\'")self.label_3.setObjectName("label_3")self.horizontalLayout_4.addWidget(self.label_3)spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_4.addItem(spacerItem2)self.pushButton_2 = QtWidgets.QPushButton(denglu)self.pushButton_2.setObjectName("pushButton_2")self.horizontalLayout_4.addWidget(self.pushButton_2)self.verticalLayout.addLayout(self.horizontalLayout_4)self.retranslateUi(denglu)def retranslateUi(self, denglu):_translate = QtCore.QCoreApplication.translatedenglu.setWindowTitle(_translate("denglu", "音樂播放器"))self.label.setText(_translate("denglu", "賬號"))self.label_2.setText(_translate("denglu", "密碼"))self.pushButton.setText(_translate("denglu", "登錄"))self.label_3.setText(_translate("denglu", "沒有賬號請先注冊>>>>>"))self.pushButton_2.setText(_translate("denglu", "注冊"))class Ui_zhuce(QWidget):def setupUi(self, zhuce):zhuce.setObjectName("zhuce")zhuce.resize(378, 230)font = QtGui.QFont()font.setBold(True)font.setWeight(75)zhuce.setFont(font)self.verticalLayout = QtWidgets.QVBoxLayout(zhuce)self.verticalLayout.setObjectName("verticalLayout")self.horizontalLayout = QtWidgets.QHBoxLayout()self.horizontalLayout.setObjectName("horizontalLayout")self.label = QtWidgets.QLabel(zhuce)self.label.setObjectName("label")self.horizontalLayout.addWidget(self.label)self.lineEdit = QtWidgets.QLineEdit(zhuce)self.lineEdit.setObjectName("lineEdit")self.horizontalLayout.addWidget(self.lineEdit)self.verticalLayout.addLayout(self.horizontalLayout)self.horizontalLayout_2 = QtWidgets.QHBoxLayout()self.horizontalLayout_2.setObjectName("horizontalLayout_2")self.label_2 = QtWidgets.QLabel(zhuce)self.label_2.setObjectName("label_2")self.horizontalLayout_2.addWidget(self.label_2)self.lineEdit_2 = QtWidgets.QLineEdit(zhuce)self.lineEdit_2.setObjectName("lineEdit_2")self.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password)self.horizontalLayout_2.addWidget(self.lineEdit_2)self.verticalLayout.addLayout(self.horizontalLayout_2)self.horizontalLayout_3 = QtWidgets.QHBoxLayout()self.horizontalLayout_3.setObjectName("horizontalLayout_3")self.label_4 = QtWidgets.QLabel(zhuce)self.label_4.setObjectName("label_4")self.horizontalLayout_3.addWidget(self.label_4)self.lineEdit_4 = QtWidgets.QLineEdit(zhuce)self.lineEdit_4.setObjectName("lineEdit_4")self.lineEdit_4.setEchoMode(QtWidgets.QLineEdit.Password)self.horizontalLayout_3.addWidget(self.lineEdit_4)self.verticalLayout.addLayout(self.horizontalLayout_3)self.horizontalLayout_4 = QtWidgets.QHBoxLayout()self.horizontalLayout_4.setObjectName("horizontalLayout_4")self.label_3 = QtWidgets.QLabel(zhuce)self.label_3.setObjectName("label_3")self.horizontalLayout_4.addWidget(self.label_3)self.lineEdit_3 = QtWidgets.QLineEdit(zhuce)self.lineEdit_3.setObjectName("lineEdit_3")self.horizontalLayout_4.addWidget(self.lineEdit_3)self.verticalLayout.addLayout(self.horizontalLayout_4)self.horizontalLayout_5 = QtWidgets.QHBoxLayout()self.horizontalLayout_5.setObjectName("horizontalLayout_5")spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_5.addItem(spacerItem)self.pushButton = QtWidgets.QPushButton(zhuce)self.pushButton.setObjectName("pushButton")self.horizontalLayout_5.addWidget(self.pushButton)spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_5.addItem(spacerItem1)self.pushButton_2 = QtWidgets.QPushButton(zhuce)self.pushButton_2.setObjectName("pushButton_2")self.horizontalLayout_5.addWidget(self.pushButton_2)spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_5.addItem(spacerItem2)self.verticalLayout.addLayout(self.horizontalLayout_5)self.retranslateUi(zhuce)QtCore.QMetaObject.connectSlotsByName(zhuce)def retranslateUi(self, zhuce):_translate = QtCore.QCoreApplication.translatezhuce.setWindowTitle(_translate("zhuce", "注冊"))self.label.setText(_translate("zhuce", "賬號    "))self.label_2.setText(_translate("zhuce", "密碼    "))self.label_4.setText(_translate("zhuce", "確認密碼"))self.label_3.setText(_translate("zhuce", "手機號  "))self.pushButton.setText(_translate("zhuce", "確定"))self.pushButton_2.setText(_translate("zhuce", "取消"))class Ui_management(QWidget):def setupUi(self, management):management.setObjectName("management")management.resize(666, 555)font = QtGui.QFont()font.setBold(True)font.setWeight(75)management.setFont(font)self.horizontalLayout_3 = QtWidgets.QHBoxLayout(management)self.horizontalLayout_3.setObjectName("horizontalLayout_3")self.verticalLayout = QtWidgets.QVBoxLayout()self.verticalLayout.setObjectName("verticalLayout")self.label = QtWidgets.QLabel(management)self.label.setAlignment(QtCore.Qt.AlignCenter)self.label.setObjectName("label")self.verticalLayout.addWidget(self.label)self.listWidget = QtWidgets.QListWidget(management)self.listWidget.setObjectName("listWidget")self.verticalLayout.addWidget(self.listWidget)self.horizontalLayout = QtWidgets.QHBoxLayout()self.horizontalLayout.setObjectName("horizontalLayout")self.pushButton = QtWidgets.QPushButton(management)self.pushButton.setObjectName("pushButton")self.horizontalLayout.addWidget(self.pushButton)self.pushButton_2 = QtWidgets.QPushButton(management)self.pushButton_2.setObjectName("pushButton_2")self.horizontalLayout.addWidget(self.pushButton_2)self.verticalLayout.addLayout(self.horizontalLayout)self.horizontalLayout_3.addLayout(self.verticalLayout)self.frame = QtWidgets.QFrame(management)self.frame.setFrameShape(QtWidgets.QFrame.VLine)self.frame.setFrameShadow(QtWidgets.QFrame.Raised)self.frame.setObjectName("frame")self.horizontalLayout_3.addWidget(self.frame)self.verticalLayout_2 = QtWidgets.QVBoxLayout()self.verticalLayout_2.setObjectName("verticalLayout_2")self.label_2 = QtWidgets.QLabel(management)self.label_2.setAlignment(QtCore.Qt.AlignCenter)self.label_2.setObjectName("label_2")self.verticalLayout_2.addWidget(self.label_2)self.listWidget_2 = QtWidgets.QListWidget(management)self.listWidget_2.setObjectName("listWidget_2")self.verticalLayout_2.addWidget(self.listWidget_2)self.horizontalLayout_2 = QtWidgets.QHBoxLayout()self.horizontalLayout_2.setObjectName("horizontalLayout_2")self.pushButton_4 = QtWidgets.QPushButton(management)self.pushButton_4.setObjectName("pushButton_4")self.horizontalLayout_2.addWidget(self.pushButton_4)self.pushButton_5 = QtWidgets.QPushButton(management)self.pushButton_5.setObjectName("pushButton_5")self.horizontalLayout_2.addWidget(self.pushButton_5)self.pushButton_6 = QtWidgets.QPushButton(management)self.pushButton_6.setObjectName("pushButton_6")self.horizontalLayout_2.addWidget(self.pushButton_6)self.verticalLayout_2.addLayout(self.horizontalLayout_2)self.horizontalLayout_3.addLayout(self.verticalLayout_2)self.retranslateUi(management)QtCore.QMetaObject.connectSlotsByName(management)def retranslateUi(self, management):_translate = QtCore.QCoreApplication.translatemanagement.setWindowTitle(_translate("management", "數據庫管理"))self.label.setText(_translate("management", "用戶管理"))self.pushButton.setText(_translate("management", "增加用戶"))self.pushButton_2.setText(_translate("management", "刪除用戶"))self.label_2.setText(_translate("management", "音樂管理"))self.pushButton_4.setText(_translate("management", "增加音樂"))self.pushButton_5.setText(_translate("management", "刪除音樂"))self.pushButton_6.setText(_translate("management", "刷新頁面"))class Ui_MusicLibrary(QWidget):def setupUi(self, MusicLibrary):MusicLibrary.setObjectName("MusicLibrary")MusicLibrary.resize(651, 481)self.verticalLayout_2 = QtWidgets.QVBoxLayout(MusicLibrary)self.verticalLayout_2.setObjectName("verticalLayout_2")self.horizontalLayout_2 = QtWidgets.QHBoxLayout()self.horizontalLayout_2.setObjectName("horizontalLayout_2")self.verticalLayout = QtWidgets.QVBoxLayout()self.verticalLayout.setObjectName("verticalLayout")self.label = QtWidgets.QLabel(MusicLibrary)self.label.setObjectName("label")self.verticalLayout.addWidget(self.label)self.listWidget = QtWidgets.QListWidget(MusicLibrary)self.listWidget.setObjectName("listWidget")self.verticalLayout.addWidget(self.listWidget)self.horizontalLayout_2.addLayout(self.verticalLayout)self.frame = QtWidgets.QFrame(MusicLibrary)self.frame.setFrameShape(QtWidgets.QFrame.VLine)self.frame.setFrameShadow(QtWidgets.QFrame.Raised)self.frame.setObjectName("frame")self.horizontalLayout_2.addWidget(self.frame)self.verticalLayout_3 = QtWidgets.QVBoxLayout()self.verticalLayout_3.setObjectName("verticalLayout_3")self.label_3 = QtWidgets.QLabel(MusicLibrary)self.label_3.setObjectName("label_3")self.verticalLayout_3.addWidget(self.label_3)self.listWidget_2 = QtWidgets.QListWidget(MusicLibrary)self.listWidget_2.setObjectName("listWidget_2")self.verticalLayout_3.addWidget(self.listWidget_2)self.horizontalLayout_2.addLayout(self.verticalLayout_3)self.verticalLayout_2.addLayout(self.horizontalLayout_2)self.frame_2 = QtWidgets.QFrame(MusicLibrary)self.frame_2.setFrameShape(QtWidgets.QFrame.HLine)self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)self.frame_2.setObjectName("frame_2")self.verticalLayout_2.addWidget(self.frame_2)self.horizontalLayout = QtWidgets.QHBoxLayout()self.horizontalLayout.setObjectName("horizontalLayout")spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout.addItem(spacerItem)self.pushButton_3 = QtWidgets.QPushButton(MusicLibrary)self.pushButton_3.setObjectName("pushButton_3")self.horizontalLayout.addWidget(self.pushButton_3)spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout.addItem(spacerItem1)self.pushButton = QtWidgets.QPushButton(MusicLibrary)self.pushButton.setObjectName("pushButton")self.horizontalLayout.addWidget(self.pushButton)spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout.addItem(spacerItem2)self.pushButton_2 = QtWidgets.QPushButton(MusicLibrary)self.pushButton_2.setObjectName("pushButton_2")self.horizontalLayout.addWidget(self.pushButton_2)spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout.addItem(spacerItem3)self.pushButton_4 = QtWidgets.QPushButton(MusicLibrary)self.pushButton_4.setObjectName("pushButton_4")self.horizontalLayout.addWidget(self.pushButton_4)spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout.addItem(spacerItem4)self.verticalLayout_2.addLayout(self.horizontalLayout)self.retranslateUi(MusicLibrary)QtCore.QMetaObject.connectSlotsByName(MusicLibrary)def retranslateUi(self, MusicLibrary):_translate = QtCore.QCoreApplication.translateMusicLibrary.setWindowTitle(_translate("MusicLibrary", "音樂播放"))self.label.setText(_translate("MusicLibrary", "音樂庫"))self.label_3.setText(_translate("MusicLibrary", "個人喜歡"))self.pushButton_3.setText(_translate("MusicLibrary", "播放"))self.pushButton.setText(_translate("MusicLibrary", "添加"))self.pushButton_2.setText(_translate("MusicLibrary", "移除"))self.pushButton_4.setText(_translate("MusicLibrary", "刷新"))class Ui_Form(QWidget):def setupUi(self, Form):Form.setObjectName("Form")Form.resize(254, 285)font = QtGui.QFont()font.setBold(True)font.setWeight(75)Form.setFont(font)self.verticalLayout = QtWidgets.QVBoxLayout(Form)self.verticalLayout.setObjectName("verticalLayout")self.horizontalLayout = QtWidgets.QHBoxLayout()self.horizontalLayout.setObjectName("horizontalLayout")self.label = QtWidgets.QLabel(Form)self.label.setObjectName("label")self.horizontalLayout.addWidget(self.label)self.lineEdit = QtWidgets.QLineEdit(Form)self.lineEdit.setObjectName("lineEdit")self.horizontalLayout.addWidget(self.lineEdit)self.verticalLayout.addLayout(self.horizontalLayout)self.horizontalLayout_3 = QtWidgets.QHBoxLayout()self.horizontalLayout_3.setObjectName("horizontalLayout_3")self.label_3 = QtWidgets.QLabel(Form)self.label_3.setObjectName("label_3")self.horizontalLayout_3.addWidget(self.label_3)self.lineEdit_3 = QtWidgets.QLineEdit(Form)self.lineEdit_3.setObjectName("lineEdit_3")self.horizontalLayout_3.addWidget(self.lineEdit_3)self.verticalLayout.addLayout(self.horizontalLayout_3)self.horizontalLayout_4 = QtWidgets.QHBoxLayout()self.horizontalLayout_4.setObjectName("horizontalLayout_4")self.label_4 = QtWidgets.QLabel(Form)self.label_4.setObjectName("label_4")self.horizontalLayout_4.addWidget(self.label_4)self.lineEdit_4 = QtWidgets.QLineEdit(Form)self.lineEdit_4.setObjectName("lineEdit_4")self.horizontalLayout_4.addWidget(self.lineEdit_4)self.verticalLayout.addLayout(self.horizontalLayout_4)self.horizontalLayout_5 = QtWidgets.QHBoxLayout()self.horizontalLayout_5.setObjectName("horizontalLayout_5")self.label_5 = QtWidgets.QLabel(Form)self.label_5.setObjectName("label_5")self.horizontalLayout_5.addWidget(self.label_5)self.lineEdit_5 = QtWidgets.QLineEdit(Form)self.lineEdit_5.setObjectName("lineEdit_5")self.horizontalLayout_5.addWidget(self.lineEdit_5)self.verticalLayout.addLayout(self.horizontalLayout_5)self.horizontalLayout_7 = QtWidgets.QHBoxLayout()self.horizontalLayout_7.setObjectName("horizontalLayout_7")spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_7.addItem(spacerItem)self.pushButton = QtWidgets.QPushButton(Form)font = QtGui.QFont()font.setBold(True)font.setWeight(75)self.pushButton.setFont(font)self.pushButton.setObjectName("pushButton")self.horizontalLayout_7.addWidget(self.pushButton)spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)self.horizontalLayout_7.addItem(spacerItem1)self.verticalLayout.addLayout(self.horizontalLayout_7)self.retranslateUi(Form)QtCore.QMetaObject.connectSlotsByName(Form)def retranslateUi(self, Form):_translate = QtCore.QCoreApplication.translateForm.setWindowTitle(_translate("Form", "管理員增加用戶"))self.label.setText(_translate("Form", "用戶名"))self.label_3.setText(_translate("Form", "密碼  "))self.label_4.setText(_translate("Form", "手機號"))self.label_5.setText(_translate("Form", "權限  "))self.pushButton.setText(_translate("Form", "確定"))class AddPeopleWindow(QWidget):def __init__(self):super().__init__()self.ui = Ui_Form()self.ui.setupUi(self)self.ui.pushButton.clicked.connect(self.queding)def queding(self):username0 = self.ui.lineEdit.text()passwd0 = self.ui.lineEdit_3.text()phone0 = self.ui.lineEdit_4.text()role0 = self.ui.lineEdit_5.text()now = datetime.now()formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")if all([username0, passwd0, phone0]):connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root',db='music_project', charset='utf8')cursor = connection.cursor()sql0 = "SELECT * FROM users WHERE username = %s AND passwd = %s AND phone_number = %s"cursor.execute(sql0, (username0, passwd0, phone0))records = cursor.fetchall()if not records:sql1 = "INSERT INTO users(username, passwd, phone_number, created_time, role) VALUES(%s, %s, %s, %s, %s)"cursor.execute(sql1, (username0, passwd0, phone0, formatted_now, '1'))connection.commit()QMessageBox.information(None, '注冊成功', f'用戶 {username0} 注冊成功', QMessageBox.Ok)cursor.close()connection.close()returnelse:text1 = '用戶已存在'else:text1 = '有空選項'QMessageBox.information(self, '提示', text1, QMessageBox.Ok)class MyWindow(QStackedWidget):def __init__(self):super().__init__()# 創建頁面self.denglu_page = Ui_denglu()self.zhuce_page = Ui_zhuce()self.musiclibrary_page=Ui_MusicLibrary()self.managerment_page=Ui_management()# 設置頁面的 UIself.denglu_widget = QWidget()self.denglu_page.setupUi(self.denglu_widget)self.zhuce_widget = QWidget()self.zhuce_page.setupUi(self.zhuce_widget)self.musiclibrary_widget = QWidget()self.musiclibrary_page.setupUi(self.musiclibrary_widget)self.managerment_widget = QWidget()self.managerment_page.setupUi(self.managerment_widget)# 添加頁面到 QStackedWidgetself.addWidget(self.denglu_widget)self.addWidget(self.zhuce_widget)self.addWidget(self.musiclibrary_widget)self.addWidget(self.managerment_widget)# 綁定按鈕的點擊事件self.denglu_page.pushButton_2.clicked.connect(self.show_registration_page)self.zhuce_page.pushButton.clicked.connect(self.show_login_page)self.zhuce_page.pushButton_2.clicked.connect(self.zhuce_cancel)self.denglu_page.pushButton.clicked.connect(self.login)self.managerment_page.pushButton.clicked.connect(self.add_people)self.managerment_page.pushButton_2.clicked.connect(self.rm_people)self.managerment_page.pushButton_4.clicked.connect(self.add_music)self.managerment_page.pushButton_5.clicked.connect(self.rm_music)self.managerment_page.pushButton_6.clicked.connect(self.set_music)self.musiclibrary_page.pushButton_3.clicked.connect(self.play_music)self.musiclibrary_page.pushButton.clicked.connect(self.add_music_to_people)self.musiclibrary_page.pushButton_2.clicked.connect(self.rm_music_from_peole)self.musiclibrary_page.pushButton_4.clicked.connect(self.flush_list)# 初始頁面self.setCurrentIndex(0)self.data={'username8':'','passwd8':'','id':''}def flush_list1(self):connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()sql = f"select * from user_favorites where uid = '{self.data['id']}' order by mid"cursor.execute(sql)list1 = cursor.fetchall()self.musiclibrary_page.listWidget_2.clear()row_str = '歌曲\t歌手\tid'self.musiclibrary_page.listWidget_2.addItem(row_str)for row in list1:sql1 = f"select * from music_library where id = '{row[1]}'"cursor.execute(sql1)list0 = cursor.fetchall()for row0 in list0:row_str = f'{row0[1]}\t{row0[2]}\t{row0[0]}'self.musiclibrary_page.listWidget_2.addItem(row_str)cursor.close()connection.close()def flush_list(self):self.flush_list1()connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()sql = 'select * from music_library order by id'cursor.execute(sql)list1 = cursor.fetchall()self.musiclibrary_page.listWidget.clear()row_str = '歌曲\t歌手\tid'self.musiclibrary_page.listWidget.addItem(row_str)for row in list1:row_str = f'{row[1]}\t{row[2]}\t{row[0]}'self.musiclibrary_page.listWidget.addItem(row_str)cursor.close()connection.close()def play_music(self):self.music_item0 = self.musiclibrary_page.listWidget_2.selectedItems()self.music_item1 = self.musiclibrary_page.listWidget.selectedItems()if not self.music_item0 and not self.music_item1:returnself.music_item = self.music_item0 if self.music_item0 else self.music_item1connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()for item in self.music_item:text = item.text()parts = text.split()mid = parts[-1] if parts else Nonesql = f"select * from music_library where id = '{mid}'"cursor.execute(sql)connection.commit()result_list = cursor.fetchall()print(result_list[0][-1])path = result_list[0][-1]print(path)music_thread = threading.Thread(target=self.music_start, args=(path,))music_thread.daemon = Truemusic_thread.start()cursor.close()connection.close()def music_start(self,path):pygame.mixer.init()pygame.mixer.music.load(path)pygame.mixer.music.play()while pygame.mixer.music.get_busy():  # 等待音頻播放完成passdef add_music_to_people(self):self.music_item = self.musiclibrary_page.listWidget.selectedItems()if not self.music_item:returnconnection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()for item in self.music_item:text = item.text()parts = text.split()mid = parts[-1]sql1 = f"select * from user_favorites where mid = '{mid}' and uid = '{self.data['id']}'"cursor.execute(sql1)result_list = cursor.fetchall()if not result_list:sql = f"insert into user_favorites(mid,uid) values('{mid}','{self.data['id']}')"cursor.execute(sql)connection.commit()cursor.close()connection.close()def rm_music_from_peole(self):self.music_item = self.musiclibrary_page.listWidget_2.selectedItems()if not self.music_item:returnconnection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()for item in self.music_item:text = item.text()parts = text.split()mid = parts[-1]print(id)sql = f"DELETE FROM user_favorites WHERE mid = '{mid}' and uid = '{self.data['id']}'"cursor.execute(sql)connection.commit()cursor.close()connection.close()def add_people(self):self.second_window = AddPeopleWindow()self.second_window.show()def rm_people(self):self.music_item = self.managerment_page.listWidget.selectedItems()for item in self.music_item:template1 = item.text()parts = template1.split()id = parts[2]connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()sql = f"delete from users where id='{id}'"cursor.execute(sql)connection.commit()cursor.close()connection.close()def add_music(self):options = QFileDialog.Options()file_path, _ = QFileDialog.getOpenFileName(self, "選擇音樂文件", "", "音樂 (*.mp3)", options=options)if file_path:match = re.search(r'([^\\/]+)-([^\\/]+)-\d+\.mp3$', file_path)if match:singer = match.group(1)song_name = match.group(2)connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root',db='music_project', charset='utf8')cursor = connection.cursor()sql0 = f"SELECT * FROM music_library WHERE artist='{singer}' AND title='{song_name}' AND file_path='{file_path}'"cursor.execute(sql0)result0 = cursor.fetchall()if not result0:sql = f"INSERT INTO music_library(artist, title, file_path) VALUES('{singer}', '{song_name}', '{file_path}')"cursor.execute(sql)connection.commit()cursor.close()connection.close()returnelse:text3='歌曲已存在'else:text3 = "沒有匹配到歌手和歌名"else:text3 = '沒有選中歌曲'QMessageBox.information(self, '提示', text3, QMessageBox.Ok)def rm_music(self):self.music_item = self.managerment_page.listWidget_2.selectedItems()if not self.music_item:returnconnection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()for item in self.music_item:text = item.text()parts = text.split()id = parts[-1]print(id)sql = "DELETE FROM music_library WHERE id = %s"cursor.execute(sql, (id,))connection.commit()cursor.close()connection.close()def set_list1(self):connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()sql = 'select * from users order by id'cursor.execute(sql)list1 = cursor.fetchall()self.managerment_page.listWidget.clear()row_str = '用戶名\t密碼\tid\t手機號\t創建時間\t\t\t最近登錄\t\t\t權限'self.managerment_page.listWidget.addItem(row_str)for row in list1:row_str = f'{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}\t{row[4]}\t{row[5]}\t{row[6]}'self.managerment_page.listWidget.addItem(row_str)cursor.close()connection.close()def set_music(self):self.set_list1()connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='music_project',charset='utf8')cursor = connection.cursor()sql = 'select * from music_library order by id'cursor.execute(sql)list1 = cursor.fetchall()self.managerment_page.listWidget_2.clear()row_str = '歌曲\t歌手\tid'self.managerment_page.listWidget_2.addItem(row_str)for row in list1:row_str = f'{row[1]}\t{row[2]}\t{row[0]}'self.managerment_page.listWidget_2.addItem(row_str)cursor.close()connection.close()# 登錄后跳轉用戶界面/管理員界面def login(self):username2 = self.denglu_page.lineEdit.text()password2 = self.denglu_page.lineEdit_2.text()if username2:if password2:connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root',db='music_project', charset='utf8')cursor = connection.cursor()sql = f"select * from users where username='{username2}' and passwd='{password2}'"cursor.execute(sql)count = cursor.fetchall()self.data['username8'] = username2self.data['passwd8'] = password2self.data['id'] = count[0][2]if count:if count[0][6] == 1:self.setCurrentIndex(2)self.resize(666, 555)else:self.setCurrentIndex(3)self.resize(555, 444)returnelse:text2='賬戶或密碼錯誤'else:text2 = '密碼為空'else:text2 = '用戶名為空'QMessageBox.information(None, '登錄失敗', text2, QMessageBox.Ok)return# 注冊取消,返回登錄頁面def zhuce_cancel(self):self.setCurrentIndex(0)self.resize(500, 300)# 登錄跳轉注冊頁面def show_registration_page(self):self.setCurrentIndex(1)self.resize(600, 400)# 注冊完,跳轉登錄頁面def show_login_page(self):# 獲取注冊信息usernames=self.zhuce_page.lineEdit.text()passwds=self.zhuce_page.lineEdit_2.text()passwds2=self.zhuce_page.lineEdit_4.text()sign=self.zhuce_page.lineEdit_3.text()now = datetime.now()formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")# 驗證注冊信息if usernames:if passwds:if passwds2:if passwds2==passwds:if sign:# 數據庫信息驗證connection = pymysql.connect(host='localhost', port=3306, user='root', passwd='root',db='music_project', charset='utf8')cursor = connection.cursor()sql = f"select * from users where phone_number='{sign}'"cursor.execute(sql)count = cursor.fetchall()if not count:sql1 = f"INSERT into users(username,passwd,phone_number,created_time,role) VALUES('{usernames}','{passwds}','{sign}','{formatted_now}','1')"cursor.execute(sql1)list=cursor.fetchall()print(list)connection.commit()QMessageBox.information(None, '注冊成功', '注冊成功,請返回登錄', QMessageBox.Ok)self.setCurrentIndex(0)self.resize(500, 300)returnelse:text1='用戶已存在,不可重復創建,注冊失敗'else:text1 ='手機號不能為空'else:text1 ='兩次密碼不一致,請重新輸入'else:text1 ='確認密碼不能為空'else:text1 ='密碼不能為空'else:text1 ='用戶名為空'QMessageBox.information(None, '注冊失敗', text1, QMessageBox.Ok)self.setCurrentIndex(1)self.resize(600, 400)if __name__ == '__main__':app = QApplication(sys.argv)window = MyWindow()window.setWindowIcon(QIcon('E:\雜物\音樂圖標.ico'))window.setWindowTitle("音樂播放器")window.resize(500, 300)window.show()sys.exit(app.exec_())

解讀代碼

首先要掌握MySQL數據庫的操作方式,最基本的增刪查改

這是存儲數據的地方,需要使用SQL語言與數據庫交互

然后是pyqt5的知識,知道如何設計界面,還有信號與槽函數

本身并不是很復雜,大部分的邏輯代碼都在處理信息方面,比如,注冊用戶的時候,用戶名不能為空,密碼不能為空,還需要手機號不同。我設計的是通過手機號排除用戶,這樣就避免了用戶取名的煩惱。在當今這個時代,一個身份證下面手機號的數量是有限的,通過手機號作為唯一標識就跟大數據時代使用身份證作為人的唯一依據。

一開始還想給用戶也設計增刪查改操作,后來發現改操作,需要再設計一個頁面,還不能直接使用注冊的頁面。

頁面的數量又增加一個。

目前的頁面有:登錄界面,注冊界面,用戶聽歌界面,管理員界面,管理員添加用戶界面。

我知道,有很多可以優化的地方,但是目前沒必要優化,我只是聯系MySQL+pyqt5僅此而已。

如果,你們想要讓我優化一下,可以在評論區評論,或者私信,我會嘗試一下。

難點

思路很簡單,但是遇到的問題一個比一個難解決。

  • qt界面跳轉功能

一開始想的是一次只展示一個界面,但是還想跳轉一下界面,比如在登錄界面,我們可以點擊注冊按鈕,跳轉到注冊界面。注冊結束之后,我們點擊確定,后臺進行數據庫比對,返回對應的信息。然后再去登錄界面。我不知道如何展示不同的界面,之前我設計的軟件都是一個界面用到結束。比如,音樂下載器,打開就是一個音樂下載界面,輸入信息,找歌。然后雙擊下載,還有翻頁什么的。都是在一個界面進行的。

用的比較高級的操作就是頁面刷新,就是多線程操作。還有動態控件設置。基本上都是基于一個界面實現的。

第一次寫多界面的軟件。才知道要使用QStackedWidget方法,把頁面緩存到堆棧,通過setCurrentIndex(1)這個方法可以跳轉到對應的界面。比如這里的5個界面,前四個都是使用頁面緩存的方式實現的。下標從0開始,對應不同的頁面。

在創建多界面的時候,還有很多要注意的地方:

  1. 主窗口需要繼承類QStackedWidget
  2. 子界面類需要繼承類QWidget
  3. 跳轉界面的時候,要使用setCurrentIndex
  4. 界面需要先實例化界面,再給每一個界面創建一個QWidget對象,界面類里面還要接收這個QWidget對象。
  5. 然后添加頁面到 QStackedWidget,把剛剛的QWidget對象在添加到QStackedWidget,使用addwidget方法。就像多行文本框一樣。也就是后續使用下標跳轉頁面的緣由。

如果你本來就會界面跳轉,那就沒什么難點了

寫到后面,又發現可以使用多窗口,也就是創建多個主窗口的方式,創建多個界面,也就是后來的管理員添加用戶界面

  • 界面設計

在設計界面的時候,一開始就想設計三個界面,一個登錄,一個注冊,一個音樂器本體。

后來沒想起來如何動態添加組件。之前使用uniapp的時候,有一個動態更新組件的方法,記混了,設計了好久,沒實現。。。

其實是能實現,但是特別麻煩。我們根據用戶的權限role,判斷是管理員還是普通用戶。然后在設計界面的邏輯部分,判斷權限。權限不同就顯示不同界面。

可能是我設計的界面不夠華麗,我感覺與其進行邏輯判斷動態更新界面,不如就直接設計兩個界面,在登錄的時候,從數據庫驗證身份后,直接就打開對應的界面。也不用邏輯判斷了。

也許,如果管理員和用戶的界面功能設計的很復雜,又很接近的情況,我會重新考慮這個部分。

  • SQL語言設計

因為涉及大量的SQL語言,也是第一次實操,避免不了遺漏或語句錯誤

為了邏輯代碼的嚴謹,每一個可能出錯的地方都要預先模擬一下。其實完全沒必要,目前的需求不在界面設計,我聽的課也就設計了一個播放界面,只有三個按鈕,對應,播放,添加,刪除功能,甚至用戶登錄都是在python的控制臺輸入的。我是實在看不下去,但也浪費了好多時間。

廢話不多說,MySQL板塊,到此為止。

下一章NoSQL數據庫—Redis數據庫。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/73344.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/73344.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/73344.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

差分專題練習 ——基于羅勇軍老師的《藍橋杯算法入門C/C++》

一、1.重新排序 - 藍橋云課 算法代碼&#xff1a; #include <bits/stdc.h> using namespace std; const int N 1e5 3;int a[N], d[N], cnt[N];int main() {int n; scanf("%d", &n);for (int i 1; i < n; i) scanf("%d", &a[i]);int m…

AI+視頻監控電力巡檢:EasyCVR視頻中臺方案如何賦能電力行業智能化轉型

隨著電力行業的快速發展&#xff0c;電力設施的安全性、穩定性和運維效率變得至關重要。傳統視頻監控系統在實時性、智能化及多系統協同等方面面臨嚴峻挑戰。EasyCVR視頻中臺解決方案作為一種先進的技術手段&#xff0c;在電力行業中得到了廣泛應用&#xff0c;為電力設施的監控…

【哈希表與字符串的算法之路:思路與實現】—— LeetCode

文章目錄 兩數之和面試題01.02.判定是否為字符重排存在重復元素存在重復元素||字母異位詞分組最長公共前綴和最長回文子串二進制求和字符串相乘 兩數之和 這題的思路很簡單&#xff0c;在讀完題目之后&#xff0c;便可以想到暴力枚舉&#xff0c;直接遍歷整個數組兩遍即可&…

RabbitMQ入門:從安裝到高級消息模式

文章目錄 一. RabbitMQ概述1.1 同步/異步1.1.1 同步調用1.1.2 異步調用 1.2 消息中間件1.2.1 概念1.2.2 作用1.2.3 常見的消息中間件1.2.4 其他中間件 1.3 RabbitMQ1.3.1 簡介1.3.2 特點1.3.3 方式1.3.4 架構1.3.5 運行流程 二. 安裝2.1 Docker 安裝 RabbitMQ 三. 簡單隊列&…

kernel與modules解耦

一、耦合&#xff1a; linux的kernel與modules存在耦合版本匹配&#xff0c;在版本不匹配&#xff08;內核重新編譯后&#xff0c;或者驅動模塊編譯依賴的內核版本跟運行版本不匹配&#xff09;時候&#xff0c;會存在insmod 驅動模塊失敗的情形&#xff1b; 二、解耦&#xff…

物理約束神經網絡(PINN)和有限元方法哪個更接近“真正的物理規律”?還是兩者只是不同的數學表達?

物理約束神經網絡(Physics-Informed Neural Networks, PINN)和有限元方法(Finite Element Method, FEM)是兩種在科學計算和工程模擬中廣泛應用的數值方法。PINN 依賴深度學習來近似微分方程的解,并在訓練過程中將物理約束作為損失項融入網絡,而 FEM 通過將連續介質的物理…

UI程序的std::cout重定向輸出到Visual Studio的debug輸出窗口

常用代碼。 UI程序的std::cout重定向輸出到Visual Studio的debug輸出窗口 #include <iostream> #include <streambuf> #include <vector> #include <string> #include <afxwin.h> //MFC// 自定義 streambuf 類&#xff0c;用于重定向輸出到 Vis…

Python開發合并多個PDF文件

前言 在我們的工作中&#xff0c;可能有以下場景需要用到合并多個PDF&#xff1a; 文檔歸檔&#xff1a;在企業或組織中&#xff0c;常常需要將相關的文檔&#xff08;如合同、報告、發票等&#xff09;合并為一個PDF文件&#xff0c;以便于歸檔和管理。 報告生成&#xff1a;在…

DeepSeek 助力 C++ 開發:探索智能編程新境界

這篇文章就會詳細講講 DeepSeek 在 C 開發里到底能怎么用&#xff0c;從上面說的寫代碼、找錯誤、優化性能&#xff0c;到管理項目這些方面&#xff0c;還會給出好多實際的代碼例子&#xff0c;講講實際用起來是啥情況。目的就是給那些做 C 開發的人&#xff0c;一份全面又詳細…

C#-使用VisualStudio編譯C#工程

一.創建csproj文件 二.創建源cs文件 三.生成解決方案 四.運行解決方案 五.VisualStudio功能列表 <1.代碼格式化: CtrlKD完成代碼整體格式化 <2.窗口布局 窗口->重置窗口布局 <3.引用查找&關聯 <4.包管理 <5.日志輸出級別 工具->選項->項目解決方案…

Kafka相關的面試題

以下是150道Kafka相關的面試題及簡潔回答&#xff1a; Kafka基礎概念 1. 什么是Kafka&#xff1f; Kafka是一個分布式、可擴展、容錯的發布-訂閱消息系統&#xff0c;最初由LinkedIn開發&#xff0c;現為Apache項目。它適用于高吞吐量的場景&#xff0c;如大數據處理和實時數據…

CTF--Web安全--SQL注入之報錯注入

CTF–Web安全–SQL注入之報錯注入 一、報錯注入的概念 用戶使用數據庫查詢語句&#xff0c;向數據庫發送錯誤指令&#xff0c;數據庫返回報錯信息&#xff0c;報錯信息中參雜著我們想要獲取的隱私數據。通常在我們在頁面顯示中找不到回顯位的時候&#xff0c;使用報錯注入。 二…

深度學習中學習率調整策略

學習率衰減策略是深度學習優化過程中的一個關鍵因素&#xff0c;它決定了訓練過程中學習率的調整方式&#xff0c;從而影響模型收斂的速度和效果。不同的衰減策略在不同的任務和模型上可能有不同的表現&#xff0c;下面從我用到過的幾個衰減策略進行記錄&#xff0c;后續慢慢跟…

JavaCV

調用攝像頭 public class Camera {public static void main(String[] args) throws FrameGrabber.Exception {// 開啟抓取器OpenCVFrameGrabber grabber new OpenCVFrameGrabber(0);grabber.start();// 開啟窗口CanvasFrame canvasFrame new CanvasFrame("OpenCV Frame…

凝思linux修改mac地址

臨時性修改 /sbin/ifconfig eth0 hw ether 00:0C:29:36:97:20

前端UI編程基礎知識:基礎三要素(結構→表現→行為)

以下是重新梳理的前端UI編程基礎知識體系&#xff0c;結合最新技術趨勢與實戰要點&#xff0c;以更適合快速掌握的邏輯結構呈現&#xff1a; 一、基礎三要素&#xff08;結構→表現→行為&#xff09; 1. HTML5 核心能力 ? 語義化標簽&#xff1a;<header>, <nav&g…

面試題:實現學生管理系統

這是我在以前面試中遇到的一個問題&#xff0c; 面試官說&#xff1a;你能現場實現一個學生管理系統嗎&#xff0c;實現對學生的增刪查改這4個功能 當時寫了半天沒寫出來.....&#xff0c;所以我在這里記錄一下 10分鐘實現學生管理系統并實現 增刪查改 功能 #include <iostr…

大語言模型基礎—語言模型的發展歷程--task1

目錄 1.語言模型的發展歷程 1.1 統計語言模型 1.2 神經語言模型 1.3 預訓練語言模型 1.4 大語言模型 1.5 總結 1.6 各階段對比與演進邏輯 1.語言模型的發展歷程 語言模型的發展歷程經歷了四個主要階段&#xff1a;統計語言模型、神經語言模型、預訓練語言模型和大語言模…

BIG_EVENT

環境準備: 開發: 跨域問題: 只有瀏覽器才存在跨域問題, 此時瀏覽器的地址和前端服務一致,所以不存在跨域問題, 但是當瀏覽器中的js代碼需要向8080發送請求時就會由于存在跨域問題而失敗. 簡單的說前端和瀏覽器的地址端口是一致的,瀏覽器只能向前端服務發送請求, 所以可以使用配…

DAY33 貪心算法Ⅱ

122. 買賣股票的最佳時機 II - 力扣&#xff08;LeetCode&#xff09; 想到把整體利潤分解為每天的利潤&#xff0c;就豁然開朗了。 class Solution { public:int maxProfit(vector<int>& prices) {int result0;for(int i1;i<prices.size();i){resultmax(0,pric…