I am writing a program using python 3.4 to allow a user to enter their Name and Surname and once they hit save the data should save in the db an display on screen. The Data saves to the db fine( I know this because every time I close the program and run it the previous entry displays). My problem here is that when I enter the data and hit save, it does not automatically display on the screen in the tabelView widget. I used QT designer 4 to create the widget and my database table only contains two columns, Full_Name and Surname. How can I get my entry to display immediately after hitting the save button?
Here's my code:
import sys
from Nametest import *
from PyQt4 import QtSql, QtGui
import mysql.connector
conn=mysql.connector.connect(host="localhost", user="root", passwd="shotokan", db="name")
cursor=conn.cursor()
def createConnection():
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName('localhost')
db.setDatabaseName('name')
db.setUserName('root')
db.setPassword('shotokan')
db.open()
print (db.lastError().text())
return True
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.model = QtSql.QSqlTableModel(self)
self.model.setTable("fullname")
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.select()
self.ui.tableView.setModel(self.model)
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()' ),self.InsertRecords)
def InsertRecords(self):
cursor.execute( """INSERT INTO fullname (First_Name, Surname)VALUES('%s','%s')""" %(self.ui.lineEdit.text(),self.ui.lineEdit_2.text()))
conn.commit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
if not createConnection():
sys.exit(1)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
Here is an image of my Widget:
Don't use 2 technologies to do the same task, if you have used QSqlTableModel to display the information then use that model to do the insert:
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.model = QtSql.QSqlTableModel(self)
self.model.setTable("fullname")
self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.model.select()
self.ui.tableView.setModel(self.model)
self.ui.pushButton.clicked.connect(self.InsertRecords)
def InsertRecords(self):
db = self.model.database()
db.transaction()
record = self.model.record()
record.setValue("First_Name", self.ui.lineEdit.text())
record.setValue("Surname", self.ui.lineEdit_2.text())
if self.model.insertRecord(-1, record):
print("successful insertion")
self.model.submitAll()
else:
db.rollback()
Note: Do not use concatenation to create a query since your application is susceptible to SQL Injection.