Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved PyQt4 and MySQL I want to learn how to insert data using QLineEdit and QPushButton

    Language Bindings
    2
    7
    3930
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • ?
      A Former User last edited by

      Can someone please teach me how to insert data in MySQL using QLineEdit and QPushButton?

      1 Reply Last reply Reply Quote 0
      • the_
        the_ last edited by

        Do you have any piece of code so far? Its hard to guess where to start without knowing what you already have/know.

        -- No support in PM --

        ? 1 Reply Last reply Reply Quote 0
        • ?
          A Former User @the_ last edited by

          @the_ i want to enter a data in QlineEdit and pass it to my database how to do it?

          import os
          import sys
          import mysql.connector
          from PyQt4.QtSql import *
          from PyQt4.QtGui import *
          from PyQt4.QtCore import *
          from PyQt4 import QtGui, QtCore

          class Window(QtGui.QMainWindow):
          def init(self):
          super(Window, self).init()
          self.setGeometry(50,50,0,0)
          self.setFixedSize(900,600)
          self.setWindowTitle("IMS Delta EarthMoving")
          self.setWindowIcon(QtGui.QIcon('delta.png'))
          pic = QtGui.QLabel(self)
          pic.setGeometry(240, -165, 698, 500)
          pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/delta2.png"))

              self.Input()
              self.search()
              self.button()
              self.database()
                   
          def search(self):
              assetSearch = QLabel("Asset search",self)
              assetSearch.move(10,10)
              AssetTag=QLineEdit(self)
              fbox=QFormLayout() 
              fbox.addRow(AssetTag)
              AssetTag.move(75,15)#left-right and up-down
              AssetTag.resize(150,20)
          
          def Input(self):
              INPUT1LABEL = QLabel("INPUT1",self)
              INPUT1LABEL.move(10,225)
              INPUT1 = QLineEdit(self)
              fbox=QFormLayout()
              fbox.addRow(INPUT1)
              INPUT1.move(75,230)
              INPUT1.resize(150,20)
            
              btnSubmit = QtGui.QPushButton("Submit",self)
              btnSubmit.clicked.connect(self.submit_function)
              btnSubmit.resize(btnSubmit.minimumSizeHint())
              btnSubmit.move(150,470)
              
          def button(self):
              btnQuit = QtGui.QPushButton("Quit", self)
              btnQuit.clicked.connect(self.close_application)
              btnQuit.resize(btnQuit.minimumSizeHint())
              btnQuit.move(150,138) #.move(left-right,top-bottom()
          
              btnSearch = QtGui.QPushButton("Search", self)
              #btnSearch.clicked.connect(self.) #add function for this ButtonBox
              btnSearch.resize(btnSearch.minimumSizeHint())
              btnSearch.move(150,40)
          
              btnUpdate = QtGui.QPushButton("Update",self)
              btnUpdate.clicked.connect(self.update_confirmation)
              btnUpdate.resize(btnUpdate.minimumSizeHint())
              btnUpdate.move(150,90)
          
              btnDelete = QtGui.QPushButton("Delete",self)
              #btnDelete.clicked.connect(self.) add function for this ButtonBox
              btnDelete.resize(btnDelete.minimumSizeHint())
              btnDelete.move(150,114)
          
              self.show()
          
          def close_application(self):
              choice = QtGui.QMessageBox.question(self, 'Exit',"Are you sure?",QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
              if choice == QtGui.QMessageBox.Yes:
                  sys.exit()
              else:
                  pass
          
          def update_confirmation(self):
              choice = QtGui.QMessageBox.question(self,'Notice!',"Are you sure?",QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
              if choice == QtGui.QMessageBox.Yes:
                  #put the function here!
                  choice = QtGui.QMessageBox.question(self,'IMS',"Query saved",QtGui.QMessageBox.Ok)
                  if choice == QtGui.QMessageBox.Ok:
                      pass
              else:
                  pass
           
          def submit_function(self):
              con = mysql.connector.connect(user="root",password="admingelo",host="localhost",database="test")
              manager = con.cursor()
              
              Date = 'Ai'
              Name = 'g'
              Sex  = 'g'
              
              insert_this_data = ("INSERT INTO test_table(name,age,sex) VALUES(%s,%s,%s)")
          
              data = (Date,Name,Sex)
          
              manager.execute(insert_this_data,data)
          
              con.commit()
              print "Insert Successful!"
          
          def database(self): #Table data view
              table 	= QTableWidget(self)
              db 	= QSqlDatabase.addDatabase("QMYSQL")
          
              db.setHostName("localhost")
              db.setDatabaseName("test")
              db.setUserName("root")
              db.setPassword("admingelo")
          
              if (db.open()==False):     
                  QMessageBox.critical(None, "Database Error",
          		    db.lastError().text())   
          		    
              query = QSqlQuery ("SELECT * FROM sfo")   
          
              table.setColumnCount(query.record().count())
              table.setRowCount(query.size())
          
              index=0
              while (query.next()):
                      table.setItem(index,0,QTableWidgetItem(query.value(0).toString()))
                      table.setItem(index,1,QTableWidgetItem(query.value(1).toString()))
                      table.setItem(index,2,QTableWidgetItem(query.value(2).toString()))
                      table.setItem(index,3,QTableWidgetItem(query.value(3).toString()))
                      table.setItem(index,4,QTableWidgetItem(query.value(4).toString()))
                      table.setItem(index,5,QTableWidgetItem(query.value(5).toString()))
                      index = index+1
          
              table.show()
              table.resize(618,360)
              table.move(240,230)
          

          def run():
          app = QtGui.QApplication(sys.argv)
          GUI = Window()
          sys.exit(app.exec_())

          run()

          1 Reply Last reply Reply Quote 0
          • the_
            the_ last edited by

            Thanks for your code sniplet (i assume you use python2.x)

            First of all in python the constructor is __init__(self) instead of init(self)

            so using

            class Window(QtGui.QMainWindow):
                def __init__(self):
                    super(Window, self).__init__()
                    self.setGeometry(50,50,0,0)
                    self.setFixedSize(900,600)
                    self.setWindowTitle("IMS Delta EarthMoving")
                    self.setWindowIcon(QtGui.QIcon('delta.png'))
                    pic = QtGui.QLabel(self)
                    pic.setGeometry(240, -165, 698, 500)
                    pic.setPixmap(QtGui.QPixmap(os.getcwd() + "/delta2.png"))
            
                    self.Input()
                    self.search()
                    self.button()
                    self.database()
            

            and

            lateron

            def run():
                app = QtGui.QApplication(sys.argv)
                GUI = Window()
            #show the GUI window
                GUI.show()
                sys.exit(app.exec_())
            
            run()
            

            brings your window to front

            I will have a look at the rest of your code a bit later

            -- No support in PM --

            ? 1 Reply Last reply Reply Quote 0
            • ?
              A Former User @the_ last edited by

              @the_ i am looking forward for that thank you sir

              1 Reply Last reply Reply Quote 0
              • the_
                the_ last edited by the_

                Had some more time to look at your piece of code. One of the problem is, that the input fields you declare are not "visible" to other class methods.

                A variable that is declared inside a method is only visible locally in this function, so you need to make it global.

                class MyClass(QWidget):
                  """
                  Constructor
                  """
                  def __init__(self):
                    initUI() #and whatever has to be called in here
                
                  """
                  A function that does all the ui setup
                  """
                  def initUI(self):
                    self.label = Qlabel("",self)
                    secondlabel = QLabel("",self)
                    button = QPushButton("Click Me",self)
                    button.clicked.connect(self.setTextValue)
                  """
                  the SLOT that is called on button click
                  """
                  def setTextValue(self):
                    self.label.setText("Button Clicked")
                    secondlabel.setText("Button Clicked") # this will throw an error, because secondlabel is not defined here
                
                def main():
                  app = QtGui.QApplication(sys.argv)
                  mywindow = MyClass()
                  sys.exit(app.exec_())
                
                if __name__ == '__main__':
                  main()
                

                Also you may use a layout on your main window and put the widgets in this layout instead of moving them around with move()

                -- No support in PM --

                ? 1 Reply Last reply Reply Quote 0
                • ?
                  A Former User @the_ last edited by

                  @the_ Thank you so much for your help ^__^

                  1 Reply Last reply Reply Quote 0
                  • First post
                    Last post