Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. [SOLVED] QSqlDatabase class question
Forum Update on Monday, May 27th 2025

[SOLVED] QSqlDatabase class question

Scheduled Pinned Locked Moved General and Desktop
sql
3 Posts 2 Posters 938 Views
  • 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.
  • L Offline
    L Offline
    lukeQt
    wrote on 25 Jun 2015, 14:48 last edited by SGaist
    #1

    Hi Everyone,

    I am getting confused how to get the database name if it is set in the main function. What am I doing wrong? I need to get the database name from the main. I can pass it as an argument in the class, but that seems like not the best approach. I tried to use QSqlDatabase.databaseName() but am confused how to access it.

               class GritPrjSetup(QtGui.QDialog, ui_grit_main_prjsetup.Ui_prjSetupDialog):
                """
                Project setup.
    
                """
    
                def __init__(self, tbl_prjinfo=None, tbl_state=None, parent=None):
                    """
                    Class Initialization.
    
                    """
    
                    super(GritPrjSetup, self).__init__(parent)
    
                    self.setupUi(self)
    
    
                    db = QtSql.QSqlDatabase()
                    print "help", db.databaseName()
                    self.query = QtSql.QSqlQuery()
    
    
                    self.test()
    
                def test(self):
                    temp = []
                    self.query.exec_("SELECT id, unit FROM unit_conv_lu")
                    while self.query.next():
                        id = self.query.value(0).toInt()[0]
                        unit = self.query.value(1).toString()
                        temp.append((id, unit))
                    print temp
    
            def main():
                """
                Set up the SQLite database connection
                Open the Tool 1 dialog
                Close the Tool 1 dialog when done
                """
                # Define application pointer in case we create our own
                app = None
    
                # Database file name
                dbfname = os.path.join(os.path.dirname(sys.argv[0]), r"DB_Testing\grit3.db")
    
                # If there is no application pointer open then create one
                if (not QtGui.QApplication.instance()):
                    app = QtGui.QApplication([])
    
    
                # This is to make sure the backend database exists. If it doesn't then exit the script.
                create = not QtCore.QFile( dbfname)
    
                # Set the database.
                db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
                db.setDatabaseName(dbfname)
                print db.databaseName()
    
                # if the database can be open then exit the script.
                if not db.open():
                    QtGui.QMessageBox.warning(None, db_file, QtCore.QString("Database Error: %1").arg(db.lastError().text()))
                    sys.exit(100)
    
                # Connect to the dialog
                my_grit1_dialog = GritPrjSetup(
                    tbl_prjinfo="project_info", tbl_state="state_lu")
                my_grit1_dialog.show() # show the dialog.
    
                # If app is not none then ensure the dialog is destroyed on exit (after
                #   the Tool 1 dialog is closed).
                if (app):
                    sys.exit(app.exec_())
    
    
            if __name__ == "__main__":
                """
                Run the code as a stand alone application, else the main function
                does not get called.
                """
    
                main()
    
    1 Reply Last reply
    0
    • S Offline
      S Offline
      SGaist
      Lifetime Qt Champion
      wrote on 25 Jun 2015, 21:41 last edited by
      #2

      Hi,

      You can use db = QtSql.QSqlDatabase.database() to get the current connection and from there retrieve the information your want.

      Hope it helps

      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
      0
      • L Offline
        L Offline
        lukeQt
        wrote on 29 Jun 2015, 15:41 last edited by
        #3

        Thank you SGaist.

        QSqlDatabase QSqlDatabase::database(const QString & connectionName = QLatin1String( defaultConnection ), bool open = true)

        Returns the database connection called connectionName. The database connection must have been previously added with addDatabase(). If open is true (the default) and the database connection is not already open it is opened now. If no connectionName is specified the default connection is used. If connectionName does not exist in the list of databases, an invalid connection is returned.

        1 Reply Last reply
        0

        1/3

        25 Jun 2015, 14:48

        • Login

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