0

Many tutorials of QSqlDatabase start a database like this:

QSqlDatabase cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id));

Would it be different from this:

QSqlDatabase cn;
cn.addDatabase("QSQLITE",QString::number(id));

or this:

QSqlDatabase cn;
cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id));
Nyaruko
  • 4,329
  • 9
  • 54
  • 105

1 Answers1

1

QSqlDatabase::addDatabase adds a database to the list of database connections and returns QSqlDatabase so

QSqlDatabase cn;
cn.addDatabase("QSQLITE",QString::number(id));

is wrong and it will not work. Of course next is correct

QSqlDatabase cn;
cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id));

It is equivalent to

QSqlDatabase cn = QSqlDatabase::addDatabase("QSQLITE",QString::number(id));

As pointed here you can call addDatabase on class instance. For example next code works too (but I don't think that we should use this):

QSqlDatabase sdb,plus;
plus = sdb.addDatabase("QSQLITE");
plus.setDatabaseName("G:/Database/test.db");

if (!plus.open())
{
       qDebug() << "not open";
}
Community
  • 1
  • 1
Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • Then is it possible to avoid the "=" operator? I want to do so because I have another problem as: http://stackoverflow.com/questions/26673955/is-this-the-safe-way-to-use-qsql-data-base-in-qt – Nyaruko Oct 31 '14 at 18:29
  • @NyarukoUnfortunately I can't help you with this question, if you will not use `=` then you will not be able to do `db.open()`, and in this case your database will not be opened, if you will use `cn.addDatabase` , you will get something like: `QSqlDatabasePrivate::database: unable to open database` – Jablonski Oct 31 '14 at 19:13