2 qq 34787995 qq_34787995 于 2016.04.25 18:33 提问

PyQt:获取lineEdit值插入到mysql失败

我想把lineEdit的输入值一边显示到tablewidegt,一边插入到mysql。由于显示程序是提取mysql的数据再显示,所以显示界面是空白,并且mysql的数据也没有改变.


    from PyQt4 import QtCore, QtGui,QtSql
    import sys
    from test2 import Ui_MainWindow
    #test2是我用QT desigenr写的UI程序
    import chardet

    class StartQt4(QtGui.QMainWindow,Ui_MainWindow):
     def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setupUi(self)
        self.db = QtSql.QSqlDatabase.addDatabase("QMYSQL") 
        self.db.setHostName("localhost")
        self.db.setDatabaseName("test")   #set address
        self.db.setUserName("root")
        self.db.setPassword("")
        if (self.db.open()):
            self.showdata()
        else:
            print "failed"
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.add)

     def add(self):
        name0 = str(self.lineEdit.text())    
        name1 = str(self.lineEdit_2.text())
        name2 = str(self.lineEdit_3.text())
        print type(name0)
        self.q=QtSql.QSqlQuery(self.db)
        self.q.exec_("insert into qiu (name0,nam1,name2) value ('%s','%s','%s')" %(''.join(name0),''.join(name1),''.join(name2)))
        self.q.exec_("commit")
        lastrow=self.tableWidget.rowCount()
        self.tableWidget.insertRow(lastrow)
        self.showdata()    

     def  showdata(self):
        q=QtSql.QSqlQuery(self.db)
        q.exec_("select * from qiu")
        for i in range(0,self.tableWidget.rowCount()):
            q.next()
            name0 = q.value(0).toString()
            name1 = q.value(1).toString()
            name2 = q.value(2).toString()
            self.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(name0))
            self.tableWidget.setItem(i, 1, QtGui.QTableWidgetItem(name1))
            self.tableWidget.setItem(i, 2, QtGui.QTableWidgetItem(name2))

    if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQt4()
    myapp.show()
    sys.exit(app.exec_())

执行结果
图片说明

1个回答

oyljerry
oyljerry   Ds   Rxr 2016.04.25 22:42

先打印sql语句 看是否语法正确

qq_34787995
qq_34787995 这条语句能实现
一年多之前 回复
qq_34787995
qq_34787995 q.exec_("insert into qiu (name0,name1,name2) value ('%s','%s','%s')" %('1','2','3'))
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!