0

I'm trying to subclass QSqlTableModel so that the constructor will set up the database that is needed for the model.

My code looks something along the lines of:

MyClass::myClass( QObject* parent, QSqlDatabase data )
    :QSqlTableModel(parent, data)
{
    auto db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if( !db.open() )
    {
        //Some debug info
    }
    if( !database().isOpen() )
    {
        // Some debug info that is called
    }
    qDebug() << database().connectionName();
    qDebug() << db.connectionName();
}

Then the constructor will output:
""
"qt_sql_default_connection"

Why are the two databases not both connected to the default connection?

LW001
  • 2,452
  • 6
  • 27
  • 36
Paul
  • 370
  • 3
  • 12

2 Answers2

1

QSqlDatabase::addDatabase:

Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName, the default connection will be the one replaced.

Amartel
  • 4,248
  • 2
  • 15
  • 21
  • Yes, and that is what I wanted, however it seems the default connection is never made when calling QSqlDatabase(). – Paul Aug 03 '15 at 12:10
  • If you want those two to be connected to the default connection name, you need to do this: `auto db = QSqlDatabase::database();`. – Amartel Aug 03 '15 at 12:28
  • But in order to get it to access a SQLite database I need to use addDatabase(as per my example), this also connects to the default database, the problem is that apparently using `myclass(this,QSqlDatabase::database())` doesn't create a database with the default connection, but just one with an invalid database. – Paul Aug 04 '15 at 06:46
  • I told you to change one exact line. Why on earth, would you change anything else? You add database **once** and then you use `QSqlDatabase::database` in order to access this opened database any time after that. – Amartel Aug 04 '15 at 07:06
  • Because I want the subclassed class to make sure a SQLite database is used and set up, not the user. But maybe I should just add the addDatabase into either the initialization or the default argument... – Paul Aug 04 '15 at 11:14
0

The answer was simple once a discussion had cleared out what was actually needed. In the declaration, instead of using
myClass( QObject* parent = nullptr, QSqlDatabase data = QSqlDatabase::database() ); I just needed to use
myClass( QObject* parent = nullptr, QSqlDatabase data = QSqlDatabase::addDatabase( "QSQLITE" ) ); Now the default option is to open a SQLite database, and if you want, you can provide another database. Thanks to Amartel for a fruitfull diskussion

Paul
  • 370
  • 3
  • 12