Python Qt Designer如何将单选按钮、下拉框数据插入MySQL
Hey Warren! I see you're getting started with PyQt5 and MySQL, and stuck on grabbing values from ComboBox and Radio Buttons to insert into your database. Let's walk through fixing your code, plus add the Radio Button functionality you mentioned (since it's missing in your original code).
First, let's fix the core issues in your original code:
- Wrong ComboBox value retrieval: Your line
dropDown = self.comboBox.addItems(self.comboBox)tries to add items (which you already did insetupUi), not get the selected value. Useself.comboBox.currentText()to fetch the selected option's text. - SQL Injection Risk: Never use string formatting (
%swith quotes) for SQL queries—this leaves you open to attacks. Use parameterized queries instead, which pymysql supports natively. - Missing Radio Button Handling: You mentioned Radio Buttons, so I'll add a set of them and show how to grab the selected one.
Here's the revised, working code with explanations:
from PyQt5 import QtCore, QtGui, QtWidgets import pymysql from PyQt5.QtWidgets import QButtonGroup # For grouping Radio Buttons class Ui_MainWindow(object): def insertData(self): # 1. Get selected ComboBox value combo_selected = self.comboBox.currentText() # 2. Get selected Radio Button value # Check if any radio button is selected first radio_selected = "" if self.radio_group.checkedButton(): radio_selected = self.radio_group.checkedButton().text() # 3. Insert data into MySQL (safe parameterized query) try: # Establish database connection conn = pymysql.connect( host="localhost", user="root", password="warren110598", database="dss" ) with conn: cur = conn.cursor() # Adjust table columns to match your schema (added 'radio_option' for radio values) sql_query = "INSERT INTO ml (rank, radio_option) VALUES (%s, %s)" # Pass values as a tuple to avoid SQL injection cur.execute(sql_query, (combo_selected, radio_selected)) conn.commit() # Save changes to database print("Data inserted successfully!") except Exception as e: print(f"Error inserting data: {str(e)}") finally: # Always close the connection if conn: conn.close() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(426, 302) MainWindow.setStyleSheet("background-color: rgb(242, 255, 225);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") # --- Your original ComboBox setup (kept intact) --- self.comboBox = QtWidgets.QComboBox(self.centralwidget) self.comboBox.setGeometry(QtCore.QRect(230, 120, 69, 22)) self.comboBox.setObjectName("comboBox") self.comboBox.addItem("") self.comboBox.addItem("") self.comboBox.addItem("") self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(110, 120, 111, 16)) self.label.setObjectName("label") # --- Add Radio Buttons (new functionality) --- # Group radio buttons so only one can be selected at a time self.radio_group = QButtonGroup(self.centralwidget) # Radio Button 1 self.radio_btn1 = QtWidgets.QRadioButton(self.centralwidget) self.radio_btn1.setGeometry(QtCore.QRect(110, 70, 100, 20)) self.radio_btn1.setText("Beginner") self.radio_group.addButton(self.radio_btn1) # Radio Button 2 self.radio_btn2 = QtWidgets.QRadioButton(self.centralwidget) self.radio_btn2.setGeometry(QtCore.QRect(230, 70, 100, 20)) self.radio_btn2.setText("Intermediate") self.radio_group.addButton(self.radio_btn2) # Radio Button 3 self.radio_btn3 = QtWidgets.QRadioButton(self.centralwidget) self.radio_btn3.setGeometry(QtCore.QRect(170, 90, 100, 20)) self.radio_btn3.setText("Expert") self.radio_group.addButton(self.radio_btn3) # --- Submit Button (your original code) --- self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(170, 170, 75, 23)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.insertData) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 426, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.comboBox.setItemText(0, _translate("MainWindow", "dae")) self.comboBox.setItemText(1, _translate("MainWindow", "eu")) self.comboBox.setItemText(2, _translate("MainWindow", "mapondo na")) self.label.setText(_translate("MainWindow", "Ma mobile legends?")) self.pushButton.setText(_translate("MainWindow", "Submit")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
Key Takeaways:
- ComboBox Value:
self.comboBox.currentText()gives you the visible text of the selected item. Useself.comboBox.currentIndex()if you need the item's position instead. - Radio Buttons: Grouping with
QButtonGroupsimplifies fetching the selected button withcheckedButton(). We added a check to handle cases where no radio button is selected. - Safe SQL Queries: Using
%sas placeholders and passing values as a tuple tocur.execute()prevents SQL injection and ensures proper data formatting. - Database Transactions: Always call
conn.commit()after inserting/updating data—without this, changes won't be saved to the database. - Error Handling: The
try-exceptblock catches connection or query errors and prints them, making debugging easier.
内容的提问来源于stack exchange,提问作者Warren Rellora
相关产品推荐
相关产品推荐

