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. QSqlDatabase add multiple databases from the same server
Forum Updated to NodeBB v4.3 + New Features

QSqlDatabase add multiple databases from the same server

Scheduled Pinned Locked Moved Solved Qt for Python
5 Posts 2 Posters 663 Views 2 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.
  • SIG_KILLS Offline
    SIG_KILLS Offline
    SIG_KILL
    wrote on last edited by
    #1

    I am making a read only database viewer, I can successfully populate a table with a database, but only with a single database at a time. I need to see all our databases.
    They are setup as System Data Sources in my ODBC manager, but looks like I cannot reference via the ODBC data source name, so I use the connection string you see bellow.

    Here is an example of my database structure:

    Server (MySql)
    │
    ├───Vacuum_CG (database)
    │   └───serial_numbers (table)
    │   └───model_numbers (table)
    │   └───calibration (table)
    │
    ├───Vacuum_IG (database)
    │   └───serial_numbers (table)
    │   └───model_numbers (table)
    │   └───calibration (table)
    │
    ├───Contract_Manufacturing (database)
    │   └───serial_numbers (table)
    │   └───model_numbers (table)
    │
    

    Here is my connection creation. This works fine if I specify a single database, but I would like to look at all 3 databases. When the app starts this function is called. This way, the connection is not kept as a member of any model classes as described in documentation.

    def create_connection():
        con = QSqlDatabase.addDatabase("QODBC")
        con.setDatabaseName(
            (
                "Driver={MySQL ODBC 8.0 ANSI Driver};"
                "Server=10.0.1.1;"
                "Port=3306;"
                "Database=Vacuum_CG,Vacuum_IG;"  # works if i only have 1 database
                "User=username;"
                "Password=super_secure_password;"
            )
        )
    
        con.setConnectOptions(
            "SQL_ATTR_ACCESS_MODE=SQL_MODE_READ_ONLY, SQL_ATTR_TRACE=SQL_OPT_TRACE_ON"
        )
        if not con.open():
            QMessageBox.critical(
                None,
                "QTableView Example - Error!",
                "Database Error: %s" % con.lastError().databaseText(),
            )
            return False
    
        return True
    

    One of the model classes (Vacuum_CG)

    class InitialResistance(QSqlTableModel):
        def __init__(self, *args, **kwargs):
            super(InitialResistance, self).__init__(*args, **kwargs)
            self.setTable("Vacuum_CG")
            self.setEditStrategy(QSqlTableModel.OnFieldChange)
            self.select()
    
        def data(self, index, role=Qt.DisplayRole):
            return QSqlTableModel.data(self, index, role)
    
        def flags(self, index):
            if not index.isValid():
                return Qt.NoItemFlags
            return Qt.ItemIsSelectable | Qt.ItemIsEnabled
    
        def filter_value(self, field: str, value: str):
            self.setFilter(f"{field.lower()}='{value.lower()}'")
    
        def remove_filter(self):
            self.setFilter("")
    
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      Use the connection name parameter of QSqlDatabase::addDatabase. That will allow you to open as many connection as you need. Note that you will need to retrieve the adequate connection when creating your QSqlTableModel objects.

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

      SIG_KILLS 1 Reply Last reply
      3
      • SGaistS SGaist

        Hi,

        Use the connection name parameter of QSqlDatabase::addDatabase. That will allow you to open as many connection as you need. Note that you will need to retrieve the adequate connection when creating your QSqlTableModel objects.

        SIG_KILLS Offline
        SIG_KILLS Offline
        SIG_KILL
        wrote on last edited by
        #3

        Hi @SGaist , thanks for the reply.

        I changed my create_connection function similar to this:

        def create_connection():
            brooks_conn = QSqlDatabase.addDatabase("QODBC", "Brooks")
            brooks_conn.setDatabaseName(CONN_BROOKS)
            brooks_conn.setConnectOptions(READ_ONLY)
        
            pin_2_pin_conn = QSqlDatabase.addDatabase("QODBC", "P2P")
            pin_2_pin_conn.setDatabaseName(CONN_PIN_2_PIN)
            pin_2_pin_conn.setConnectOptions(READ_ONLY)
        

        I can confirm the table model is able to see the proper connection names, although I cannot figure out how to specify a particular database for the table model.
        Between the PySide6 docs and the C++ docs, I could not find an example of opening a specific connection. However, if it is specified in the C++ docs, there is a good its not jumping out at me as I am very green when it comes to C++.

        class BurnInModel(QSqlTableModel):
            def __init__(self, *args, **kwargs):
                super(BurnInModel, self).__init__(*args, **kwargs)
                print(QSqlDatabase.connectionNames())  # Prints: ['P2P', 'Brooks']
        
                # If anything is wrong, it is surely this line
                self.database().open("QODBC", "Brooks")
        
                self.setTable(_burn_in_view_name)
                self.setEditStrategy(QSqlTableModel.OnFieldChange)
                print(self.database().connectionName())  # Prints: ''
                self.select()
        
        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          The QSqlTableModel constructor documentation shows that it's the second parameter.

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

          SIG_KILLS 1 Reply Last reply
          2
          • SGaistS SGaist

            The QSqlTableModel constructor documentation shows that it's the second parameter.

            SIG_KILLS Offline
            SIG_KILLS Offline
            SIG_KILL
            wrote on last edited by
            #5

            @SGaist

            Thanks for the help, and the link to that specific argument, I see what I did wrong.
            I really appreciate you! :D

            1 Reply Last reply
            0

            • Login

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