如何读取 QComboBox 数据并将其存储到 mysql 数据库中

How to read QComboBox data and storesit into mysql database

如何从 QComboBox 中获取选定的项目,以及如何在单击按钮时将组合框的选定项目存储到数据库中...

import MySQLdb    
import sys    
from PyQt4.QtCore import *    
from PyQt4.QtGui import *

def win():

    db=MySQLdb.connect('localhost','root','Suhel786','radio')    
    cursor=db.cursor()    

    app=QApplication(sys.argv)    

    w=QWidget()    
    co=QComboBox()    
    co.addItem("A+")    
    co.addItem("A-")    
    b1 = QPushButton("Tap it!")    
    w.setWindowTitle("Combo")    
    hbox=QHBoxLayout()    
    hbox.addWidget(co)    
    hbox.addWidget(b1)

    b1.clicked.connect(b1_action)

    w.setLayout(hbox)

    w.show()

    db.commit()    
    db.close()

    sys.exit(app.exec_())

def b1_action():    
    print "data is inserted"        

win()

你必须将按钮的clicked信号连接到某个插槽,在这种情况下插槽将是保存方法,在这个函数中我们将通过currentText()方法获取选定的文本QComboBox,并将其插入数据库,如下所示:

class Win(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.db = MySQLdb.connect('localhost','root','Suhel786','radio')
        self.cursor = self.db.cursor()

        self.db.commit()
        self.setLayout(QHBoxLayout())
        self.btn = QPushButton("Save", self)
        self.combo = QComboBox(self)
        self.combo.addItems(["A+", "A-", "AB-"])
        self.layout().addWidget(self.btn)
        self.layout().addWidget(self.combo)
        self.btn.clicked.connect(self.save)

    def save(self):
        text = self.combo.currentText()
        self.cursor.execute("INSERT INTO test (Blood) values('{}')".format(text))
        self.db.commit()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Win()
    w.show()
    sys.exit(app.exec_())