Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Using QtSql.QSqlQuery() and where to search for a string in a table
Forum Updated to NodeBB v4.3 + New Features

Using QtSql.QSqlQuery() and where to search for a string in a table

Scheduled Pinned Locked Moved Unsolved Qt for Python
29 Posts 4 Posters 2.4k Views 1 Watching
  • 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.
  • P Offline
    P Offline
    PythonQTMarlem
    wrote on 1 Sept 2022, 15:54 last edited by
    #1

    Hello,
    Here my code:

    def sql_statement(self):
            query = QtSql.QSqlQuery()
            suchstring = "Brunhilde"
            abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
            query.exec(abfrage)
            print("SQL Statement abgesetzt!")
    

    There is no error message, but the select is not executed either.

    Question: how does it work properly?

    J 1 Reply Last reply 1 Sept 2022, 18:35
    0
    • S Offline
      S Offline
      SGaist
      Lifetime Qt Champion
      wrote on 1 Sept 2022, 18:11 last edited by
      #2

      Hi,

      There's no error message because you are not doing any error checks nor printing any results.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      1
      • P PythonQTMarlem
        1 Sept 2022, 15:54

        Hello,
        Here my code:

        def sql_statement(self):
                query = QtSql.QSqlQuery()
                suchstring = "Brunhilde"
                abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                query.exec(abfrage)
                print("SQL Statement abgesetzt!")
        

        There is no error message, but the select is not executed either.

        Question: how does it work properly?

        J Offline
        J Offline
        JonB
        wrote on 1 Sept 2022, 18:35 last edited by JonB 9 Jan 2022, 18:36
        #3

        @PythonQTMarlem
        If you qDebug() << abfrage and look at it (and think about it) you might even see what is wrong in the query above.

        1 Reply Last reply
        0
        • P Offline
          P Offline
          PythonQTMarlem
          wrote on 2 Sept 2022, 04:49 last edited by
          #4

          Thank you for your answer.
          I try this:

              def sql_statement(self):
                  query = QtSql.QSqlQuery()
                  suchstring = "Brunhilde"
                  abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                  try:
                    query.exec(abfrage)
                  except Exception as err:
                      qDebug(str(err))
                  print("SQL Statement abgesetzt!")
          
          

          But there is no Error Messaage.

          Here my whole code:

          import sys
          from PyQt6 import QtGui, QtSql
          from PyQt6.QtSql import QSqlDatabase, QSqlRelation, QSqlTableModel, QSqlRelationalTableModel
          from PyQt6.QtWidgets import QWidget, QApplication, QFormLayout, QTableView, QPushButton
          from PyQt6.QtCore import Qt, qDebug
          
          
          class FensterKlasse(QWidget):
              def __init__(self):
                  super().__init__()
                  self.table_model = QSqlRelationalTableModel()
                  self.table_model.setTable("telefon_verwaltung")
          
                  # Spaltenüberschriften anpassen
                  self.table_model.setHeaderData(1, Qt.Orientation.Horizontal, "Vorname")
                  self.table_model.setHeaderData(2, Qt.Orientation.Horizontal, "Nachname")
                  self.table_model.setHeaderData(3, Qt.Orientation.Horizontal, "Telefonnummer")
          
                  # Datenbank-Anzeigen
                  self.table_model.select()
                  self.tabellengrid = QTableView()
                  self.tabellengrid.setModel(self.table_model)
          
                  # Spaltenbreiten anpassen
                  self.tabellengrid.setColumnWidth(0, 2)
                  self.tabellengrid.setColumnHidden(0, True)
                  self.tabellengrid.setColumnWidth(1, 100)
                  self.tabellengrid.setColumnWidth(2, 150)
                  self.tabellengrid.setColumnWidth(3, 130)
                  self.GUI()
          
              def GUI(self):
                  self.setWindowTitle("PyQt6 Telefonnummer-Verwaltung mit Datenbank")
                  self.setGeometry(0, 0, 500, 500)
                  qtRectangle = self.frameGeometry()
                  centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
                  qtRectangle.moveCenter(centerPoint)
                  self.move(qtRectangle.topLeft())
          
                  formLayout = QFormLayout()
                  btnSuchen = QPushButton("&Suchen", self)
                  btnSuchen.clicked.connect(self.sql_statement)
          
                  formLayout.addRow(self.tabellengrid)
                  formLayout.addRow(btnSuchen)
                  self.setLayout(formLayout)
          
              def sql_statement(self):
                  query = QtSql.QSqlQuery()
                  suchstring = "Brunhilde"
                  abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                  try:
                    query.exec(abfrage)
                  except Exception as err:
                      qDebug(str(err))
                  print("SQL Statement abgesetzt!")
          
          
          def programm_beeden(self):
              QApplication.instance().quit()
          
          
          app = QApplication([])
          db = QSqlDatabase.addDatabase("QSQLITE")
          db.setDatabaseName("telefonnummern_verwaltung.db")
          
          fenster = FensterKlasse()
          
          if __name__ == '__main__':
              fenster.show()
              sys.exit(app.exec())
          
          

          My suspicion is that the query has no connection to the database at all. Can this be?

          J J 2 Replies Last reply 2 Sept 2022, 06:20
          0
          • P PythonQTMarlem
            2 Sept 2022, 04:49

            Thank you for your answer.
            I try this:

                def sql_statement(self):
                    query = QtSql.QSqlQuery()
                    suchstring = "Brunhilde"
                    abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                    try:
                      query.exec(abfrage)
                    except Exception as err:
                        qDebug(str(err))
                    print("SQL Statement abgesetzt!")
            
            

            But there is no Error Messaage.

            Here my whole code:

            import sys
            from PyQt6 import QtGui, QtSql
            from PyQt6.QtSql import QSqlDatabase, QSqlRelation, QSqlTableModel, QSqlRelationalTableModel
            from PyQt6.QtWidgets import QWidget, QApplication, QFormLayout, QTableView, QPushButton
            from PyQt6.QtCore import Qt, qDebug
            
            
            class FensterKlasse(QWidget):
                def __init__(self):
                    super().__init__()
                    self.table_model = QSqlRelationalTableModel()
                    self.table_model.setTable("telefon_verwaltung")
            
                    # Spaltenüberschriften anpassen
                    self.table_model.setHeaderData(1, Qt.Orientation.Horizontal, "Vorname")
                    self.table_model.setHeaderData(2, Qt.Orientation.Horizontal, "Nachname")
                    self.table_model.setHeaderData(3, Qt.Orientation.Horizontal, "Telefonnummer")
            
                    # Datenbank-Anzeigen
                    self.table_model.select()
                    self.tabellengrid = QTableView()
                    self.tabellengrid.setModel(self.table_model)
            
                    # Spaltenbreiten anpassen
                    self.tabellengrid.setColumnWidth(0, 2)
                    self.tabellengrid.setColumnHidden(0, True)
                    self.tabellengrid.setColumnWidth(1, 100)
                    self.tabellengrid.setColumnWidth(2, 150)
                    self.tabellengrid.setColumnWidth(3, 130)
                    self.GUI()
            
                def GUI(self):
                    self.setWindowTitle("PyQt6 Telefonnummer-Verwaltung mit Datenbank")
                    self.setGeometry(0, 0, 500, 500)
                    qtRectangle = self.frameGeometry()
                    centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
                    qtRectangle.moveCenter(centerPoint)
                    self.move(qtRectangle.topLeft())
            
                    formLayout = QFormLayout()
                    btnSuchen = QPushButton("&Suchen", self)
                    btnSuchen.clicked.connect(self.sql_statement)
            
                    formLayout.addRow(self.tabellengrid)
                    formLayout.addRow(btnSuchen)
                    self.setLayout(formLayout)
            
                def sql_statement(self):
                    query = QtSql.QSqlQuery()
                    suchstring = "Brunhilde"
                    abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                    try:
                      query.exec(abfrage)
                    except Exception as err:
                        qDebug(str(err))
                    print("SQL Statement abgesetzt!")
            
            
            def programm_beeden(self):
                QApplication.instance().quit()
            
            
            app = QApplication([])
            db = QSqlDatabase.addDatabase("QSQLITE")
            db.setDatabaseName("telefonnummern_verwaltung.db")
            
            fenster = FensterKlasse()
            
            if __name__ == '__main__':
                fenster.show()
                sys.exit(app.exec())
            
            

            My suspicion is that the query has no connection to the database at all. Can this be?

            J Offline
            J Offline
            jsulm
            Lifetime Qt Champion
            wrote on 2 Sept 2022, 06:20 last edited by
            #5

            @PythonQTMarlem said in Using QtSql.QSqlQuery() and where to search for a string in a table:

            But there is no Error Messaage.

            Qt does not use exceptions.
            If you would have spent a minute to read documentation you would have found this: https://doc.qt.io/qt-6/qsqlquery.html#lastError
            Did you aopen the default connection before executing the query?

            https://forum.qt.io/topic/113070/qt-code-of-conduct

            P 1 Reply Last reply 2 Sept 2022, 09:48
            0
            • P PythonQTMarlem
              2 Sept 2022, 04:49

              Thank you for your answer.
              I try this:

                  def sql_statement(self):
                      query = QtSql.QSqlQuery()
                      suchstring = "Brunhilde"
                      abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                      try:
                        query.exec(abfrage)
                      except Exception as err:
                          qDebug(str(err))
                      print("SQL Statement abgesetzt!")
              
              

              But there is no Error Messaage.

              Here my whole code:

              import sys
              from PyQt6 import QtGui, QtSql
              from PyQt6.QtSql import QSqlDatabase, QSqlRelation, QSqlTableModel, QSqlRelationalTableModel
              from PyQt6.QtWidgets import QWidget, QApplication, QFormLayout, QTableView, QPushButton
              from PyQt6.QtCore import Qt, qDebug
              
              
              class FensterKlasse(QWidget):
                  def __init__(self):
                      super().__init__()
                      self.table_model = QSqlRelationalTableModel()
                      self.table_model.setTable("telefon_verwaltung")
              
                      # Spaltenüberschriften anpassen
                      self.table_model.setHeaderData(1, Qt.Orientation.Horizontal, "Vorname")
                      self.table_model.setHeaderData(2, Qt.Orientation.Horizontal, "Nachname")
                      self.table_model.setHeaderData(3, Qt.Orientation.Horizontal, "Telefonnummer")
              
                      # Datenbank-Anzeigen
                      self.table_model.select()
                      self.tabellengrid = QTableView()
                      self.tabellengrid.setModel(self.table_model)
              
                      # Spaltenbreiten anpassen
                      self.tabellengrid.setColumnWidth(0, 2)
                      self.tabellengrid.setColumnHidden(0, True)
                      self.tabellengrid.setColumnWidth(1, 100)
                      self.tabellengrid.setColumnWidth(2, 150)
                      self.tabellengrid.setColumnWidth(3, 130)
                      self.GUI()
              
                  def GUI(self):
                      self.setWindowTitle("PyQt6 Telefonnummer-Verwaltung mit Datenbank")
                      self.setGeometry(0, 0, 500, 500)
                      qtRectangle = self.frameGeometry()
                      centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
                      qtRectangle.moveCenter(centerPoint)
                      self.move(qtRectangle.topLeft())
              
                      formLayout = QFormLayout()
                      btnSuchen = QPushButton("&Suchen", self)
                      btnSuchen.clicked.connect(self.sql_statement)
              
                      formLayout.addRow(self.tabellengrid)
                      formLayout.addRow(btnSuchen)
                      self.setLayout(formLayout)
              
                  def sql_statement(self):
                      query = QtSql.QSqlQuery()
                      suchstring = "Brunhilde"
                      abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring
                      try:
                        query.exec(abfrage)
                      except Exception as err:
                          qDebug(str(err))
                      print("SQL Statement abgesetzt!")
              
              
              def programm_beeden(self):
                  QApplication.instance().quit()
              
              
              app = QApplication([])
              db = QSqlDatabase.addDatabase("QSQLITE")
              db.setDatabaseName("telefonnummern_verwaltung.db")
              
              fenster = FensterKlasse()
              
              if __name__ == '__main__':
                  fenster.show()
                  sys.exit(app.exec())
              
              

              My suspicion is that the query has no connection to the database at all. Can this be?

              J Offline
              J Offline
              JonB
              wrote on 2 Sept 2022, 06:38 last edited by
              #6

              @PythonQTMarlem said in Using QtSql.QSqlQuery() and where to search for a string in a table:

              My suspicion is that the query has no connection to the database at all. Can this be?

              That is as may be (see @jsulm's reply), but as I said if you look at your generated SELECT statement it is syntactically incorrect so it is not going to work anyway....

              P 1 Reply Last reply 2 Sept 2022, 09:53
              0
              • J jsulm
                2 Sept 2022, 06:20

                @PythonQTMarlem said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                But there is no Error Messaage.

                Qt does not use exceptions.
                If you would have spent a minute to read documentation you would have found this: https://doc.qt.io/qt-6/qsqlquery.html#lastError
                Did you aopen the default connection before executing the query?

                P Offline
                P Offline
                PythonQTMarlem
                wrote on 2 Sept 2022, 09:48 last edited by
                #7

                @jsulm
                I've spent a lot of time reading Qt documentation, but you have to find the right places. Also, I was just trying to implement what SGaist advised me to do. Since data is displayed in the QTableView at the time the query is executed, I assumed that the connection to the database was established.

                1 Reply Last reply
                0
                • J JonB
                  2 Sept 2022, 06:38

                  @PythonQTMarlem said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                  My suspicion is that the query has no connection to the database at all. Can this be?

                  That is as may be (see @jsulm's reply), but as I said if you look at your generated SELECT statement it is syntactically incorrect so it is not going to work anyway....

                  P Offline
                  P Offline
                  PythonQTMarlem
                  wrote on 2 Sept 2022, 09:53 last edited by
                  #8

                  @JonB Yes, but that was exactly the reason why I asked this question here. I couldn't find an example via google using select where and querying for a string.

                  1 Reply Last reply
                  0
                  • P Offline
                    P Offline
                    PythonQTMarlem
                    wrote on 2 Sept 2022, 10:01 last edited by
                    #9

                    I try this in SQL_LightStudio:

                    SELECT * FROM telefon_verwaltung WHERE vorname='Brunhilde'
                    

                    it Works. But I don't know how to write this in Python, 'cause I found no example.

                    J 1 Reply Last reply 2 Sept 2022, 10:55
                    0
                    • P PythonQTMarlem
                      2 Sept 2022, 10:01

                      I try this in SQL_LightStudio:

                      SELECT * FROM telefon_verwaltung WHERE vorname='Brunhilde'
                      

                      it Works. But I don't know how to write this in Python, 'cause I found no example.

                      J Offline
                      J Offline
                      JonB
                      wrote on 2 Sept 2022, 10:55 last edited by
                      #10

                      @PythonQTMarlem
                      You don't need an example! Why do you need an example for everything? You just need to change your line to produce that.....

                      P 1 Reply Last reply 2 Sept 2022, 12:00
                      0
                      • S Offline
                        S Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on 2 Sept 2022, 11:14 last edited by
                        #11

                        So:

                        SELECT * FROM telefon_verwaltung WHERE vorname='Brunhilde'

                        This is the query you want.

                        Now:

                        suchstring = "Brunhilde"
                        abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring

                        This produces:

                        SELECT * FROM telefon_verwaltung WHERE vorname=Brunhilde

                        Do you spot the issue ?

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        P 1 Reply Last reply 2 Sept 2022, 11:57
                        1
                        • S SGaist
                          2 Sept 2022, 11:14

                          So:

                          SELECT * FROM telefon_verwaltung WHERE vorname='Brunhilde'

                          This is the query you want.

                          Now:

                          suchstring = "Brunhilde"
                          abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname=" + suchstring

                          This produces:

                          SELECT * FROM telefon_verwaltung WHERE vorname=Brunhilde

                          Do you spot the issue ?

                          P Offline
                          P Offline
                          PythonQTMarlem
                          wrote on 2 Sept 2022, 11:57 last edited by
                          #12

                          @SGaist said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                          suchstring

                          Yes, I'm missing the quotation marks before and after suchstring. But I don't know how to do that and I couldn't find anything on google that worked for me.

                          J 1 Reply Last reply 2 Sept 2022, 12:48
                          0
                          • J JonB
                            2 Sept 2022, 10:55

                            @PythonQTMarlem
                            You don't need an example! Why do you need an example for everything? You just need to change your line to produce that.....

                            P Offline
                            P Offline
                            PythonQTMarlem
                            wrote on 2 Sept 2022, 12:00 last edited by
                            #13

                            @JonB If you don't know something, the best way to learn is through examples. I know Java, C# and Python, but I just don't always understand what the documentation says. If I see an example, then I understand :)

                            J 1 Reply Last reply 2 Sept 2022, 12:09
                            0
                            • P PythonQTMarlem
                              2 Sept 2022, 12:00

                              @JonB If you don't know something, the best way to learn is through examples. I know Java, C# and Python, but I just don't always understand what the documentation says. If I see an example, then I understand :)

                              J Offline
                              J Offline
                              jsulm
                              Lifetime Qt Champion
                              wrote on 2 Sept 2022, 12:09 last edited by
                              #14

                              @PythonQTMarlem

                              abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname='" + suchstring + "'"
                              

                              https://forum.qt.io/topic/113070/qt-code-of-conduct

                              P 1 Reply Last reply 2 Sept 2022, 17:46
                              0
                              • P PythonQTMarlem
                                2 Sept 2022, 11:57

                                @SGaist said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                                suchstring

                                Yes, I'm missing the quotation marks before and after suchstring. But I don't know how to do that and I couldn't find anything on google that worked for me.

                                J Offline
                                J Offline
                                JonB
                                wrote on 2 Sept 2022, 12:48 last edited by JonB 9 Feb 2022, 12:48
                                #15

                                @PythonQTMarlem said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                                Yes, I'm missing the quotation marks before and after suchstring.

                                I know Java, C# and Python

                                Sorry, but then you do know how to put quotation marks into a Python literal string. It's also the same in C#, Java & C++.

                                1 Reply Last reply
                                0
                                • J jsulm
                                  2 Sept 2022, 12:09

                                  @PythonQTMarlem

                                  abfrage = "SELECT * FROM telefon_verwaltung WHERE vorname='" + suchstring + "'"
                                  
                                  P Offline
                                  P Offline
                                  PythonQTMarlem
                                  wrote on 2 Sept 2022, 17:46 last edited by
                                  #16

                                  @jsulm Thanks your solution works. But my query still doesn't deliver the desired result.

                                  J 1 Reply Last reply 2 Sept 2022, 18:26
                                  0
                                  • P PythonQTMarlem
                                    2 Sept 2022, 17:46

                                    @jsulm Thanks your solution works. But my query still doesn't deliver the desired result.

                                    J Offline
                                    J Offline
                                    JonB
                                    wrote on 2 Sept 2022, 18:26 last edited by
                                    #17

                                    @PythonQTMarlem
                                    Do you want to show us your relevant code now? With the correct SELECT, then what do you do after the query.exec() to check its result and read any rows returned?

                                    1 Reply Last reply
                                    0
                                    • P Offline
                                      P Offline
                                      PythonQTMarlem
                                      wrote on 4 Sept 2022, 19:26 last edited by
                                      #18

                                      I found out. Here my solution:

                                      import os
                                      import sys
                                      from PyQt6 import QtGui, QtSql
                                      from PyQt6.QtSql import QSqlDatabase, QSqlQueryModel
                                      from PyQt6.QtWidgets import QWidget, QApplication, QFormLayout, QTableView, QPushButton, QMessageBox, QLineEdit
                                      from PyQt6.QtCore import Qt, qDebug
                                      
                                      class FensterKlasse(QWidget):
                                          def __init__(self):
                                              super().__init__()
                                              filename = os.path.join(os.path.dirname(__file__), "telefonnummern_verwaltung.db")
                                      
                                              db = QSqlDatabase.addDatabase('QSQLITE')
                                              db.setDatabaseName(filename)
                                              if db.open():
                                                  self.table_model = QSqlQueryModel()
                                      
                                                  # Datenbank-Anzeigen
                                                  self.table_model.setQuery("SELECT * FROM `telefon_verwaltung`")
                                                  self.tabellengrid = QTableView()
                                                  self.tabellengrid.setModel(self.table_model)
                                      
                                                  # Spaltenüberschriften anpassen
                                                  self.table_model.setHeaderData(1, Qt.Orientation.Horizontal, "Vorname")
                                                  self.table_model.setHeaderData(2, Qt.Orientation.Horizontal, "Nachname")
                                                  self.table_model.setHeaderData(3, Qt.Orientation.Horizontal, "Telefonnummer")
                                      
                                                  # Spaltenbreiten anpassen
                                                  self.tabellengrid.setColumnWidth(0, 2)
                                                  self.tabellengrid.setColumnHidden(0, True)
                                                  self.tabellengrid.setColumnWidth(1, 100)
                                                  self.tabellengrid.setColumnWidth(2, 150)
                                                  self.tabellengrid.setColumnWidth(3, 130)
                                      
                                                  self.GUI()
                                                  return
                                      
                                          def GUI(self):
                                              self.setWindowTitle("PyQt6 Telefonnummer-Verwaltung mit Datenbank")
                                              self.setGeometry(0, 0, 500, 500)
                                              qtRectangle = self.frameGeometry()
                                              centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
                                              qtRectangle.moveCenter(centerPoint)
                                              self.move(qtRectangle.topLeft())
                                      
                                              self.suchefeld = QLineEdit(self)
                                              self.suche_starten_button = QPushButton("&Suche starten", self)
                                              self.suche_starten_button.clicked.connect(self.suche_starten)
                                              formLayout = QFormLayout()
                                              formLayout.addRow(self.tabellengrid)
                                              formLayout.addRow(self.suchefeld, self.suche_starten_button)
                                              self.setLayout(formLayout)
                                      
                                          def suche_starten(self):
                                              suchwert = self.suchefeld.text()
                                              if suchwert == '':
                                                  self.table_model.setQuery("SELECT * FROM `telefon_verwaltung`")
                                              else:
                                                  self.table_model.setQuery("SELECT * FROM `telefon_verwaltung` where nachname='" + suchwert + "'")
                                      
                                      
                                      def programm_beeden(self):
                                          QApplication.instance().quit()
                                      
                                      app = QApplication([])
                                      fenster = FensterKlasse()
                                      
                                      if __name__ == '__main__':
                                          fenster.show()
                                          sys.exit(app.exec())
                                      
                                      

                                      The problem is that the result set is not editable. I still have to find out how to search and edit at the same time. But my question in this thread is solved!

                                      J 1 Reply Last reply 4 Sept 2022, 19:28
                                      0
                                      • P PythonQTMarlem
                                        4 Sept 2022, 19:26

                                        I found out. Here my solution:

                                        import os
                                        import sys
                                        from PyQt6 import QtGui, QtSql
                                        from PyQt6.QtSql import QSqlDatabase, QSqlQueryModel
                                        from PyQt6.QtWidgets import QWidget, QApplication, QFormLayout, QTableView, QPushButton, QMessageBox, QLineEdit
                                        from PyQt6.QtCore import Qt, qDebug
                                        
                                        class FensterKlasse(QWidget):
                                            def __init__(self):
                                                super().__init__()
                                                filename = os.path.join(os.path.dirname(__file__), "telefonnummern_verwaltung.db")
                                        
                                                db = QSqlDatabase.addDatabase('QSQLITE')
                                                db.setDatabaseName(filename)
                                                if db.open():
                                                    self.table_model = QSqlQueryModel()
                                        
                                                    # Datenbank-Anzeigen
                                                    self.table_model.setQuery("SELECT * FROM `telefon_verwaltung`")
                                                    self.tabellengrid = QTableView()
                                                    self.tabellengrid.setModel(self.table_model)
                                        
                                                    # Spaltenüberschriften anpassen
                                                    self.table_model.setHeaderData(1, Qt.Orientation.Horizontal, "Vorname")
                                                    self.table_model.setHeaderData(2, Qt.Orientation.Horizontal, "Nachname")
                                                    self.table_model.setHeaderData(3, Qt.Orientation.Horizontal, "Telefonnummer")
                                        
                                                    # Spaltenbreiten anpassen
                                                    self.tabellengrid.setColumnWidth(0, 2)
                                                    self.tabellengrid.setColumnHidden(0, True)
                                                    self.tabellengrid.setColumnWidth(1, 100)
                                                    self.tabellengrid.setColumnWidth(2, 150)
                                                    self.tabellengrid.setColumnWidth(3, 130)
                                        
                                                    self.GUI()
                                                    return
                                        
                                            def GUI(self):
                                                self.setWindowTitle("PyQt6 Telefonnummer-Verwaltung mit Datenbank")
                                                self.setGeometry(0, 0, 500, 500)
                                                qtRectangle = self.frameGeometry()
                                                centerPoint = QtGui.QGuiApplication.primaryScreen().availableGeometry().center()
                                                qtRectangle.moveCenter(centerPoint)
                                                self.move(qtRectangle.topLeft())
                                        
                                                self.suchefeld = QLineEdit(self)
                                                self.suche_starten_button = QPushButton("&Suche starten", self)
                                                self.suche_starten_button.clicked.connect(self.suche_starten)
                                                formLayout = QFormLayout()
                                                formLayout.addRow(self.tabellengrid)
                                                formLayout.addRow(self.suchefeld, self.suche_starten_button)
                                                self.setLayout(formLayout)
                                        
                                            def suche_starten(self):
                                                suchwert = self.suchefeld.text()
                                                if suchwert == '':
                                                    self.table_model.setQuery("SELECT * FROM `telefon_verwaltung`")
                                                else:
                                                    self.table_model.setQuery("SELECT * FROM `telefon_verwaltung` where nachname='" + suchwert + "'")
                                        
                                        
                                        def programm_beeden(self):
                                            QApplication.instance().quit()
                                        
                                        app = QApplication([])
                                        fenster = FensterKlasse()
                                        
                                        if __name__ == '__main__':
                                            fenster.show()
                                            sys.exit(app.exec())
                                        
                                        

                                        The problem is that the result set is not editable. I still have to find out how to search and edit at the same time. But my question in this thread is solved!

                                        J Offline
                                        J Offline
                                        JonB
                                        wrote on 4 Sept 2022, 19:28 last edited by
                                        #19

                                        @PythonQTMarlem
                                        To be able to make updates to a table you will want to change from QSqlQueryModel to QSqlTableModel.

                                        1 Reply Last reply
                                        1
                                        • P Offline
                                          P Offline
                                          PythonQTMarlem
                                          wrote on 5 Sept 2022, 13:15 last edited by
                                          #20

                                          @JonB said in Using QtSql.QSqlQuery() and where to search for a string in a table:

                                          QSqlTableModel

                                          Thank you. But its not so easy.
                                          on this code:

                                          self.table_model.setQuery("SELECT * FROM telefon_verwaltung")
                                          

                                          I got the errormessage:
                                          TypeError: setQuery(self, QSqlQuery): argument 1 has unexpected type 'str'

                                          Now I try a typecast:

                                          self.table_model.setQuery(QSqlQuery("SELECT * FROM telefon_verwaltung"))
                                          

                                          The application crashed with:
                                          Process finished with exit code -1073740791 (0xC0000409)

                                          Can you please tell me what I have to do?

                                          J 1 Reply Last reply 5 Sept 2022, 13:28
                                          0

                                          1/29

                                          1 Sept 2022, 15:54

                                          • Login

                                          • Login or register to search.
                                          1 out of 29
                                          • First post
                                            1/29
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved