Multiple classes DataBase connection
-
Hello! I'm new to Qt and I'm writing an application which interacts with database and have multiple QDialogs in it. What is an optimal way to connect all my classes with database? I mean, should I create a global connection class or just connect to database in every class separately from others? If it's better to create a global connection class, how to do that?
-
Hi and welcome to the forums.-
If you mean to access the same database from multiple classes,
then Qt already can do this for you.bool createConnection() { QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); << << Looks like a local var but is kept internally db.setDatabaseName(":memory:"); // db.setDatabaseName("c:\\folder\\test.db"); if (!db.open()) { QMessageBox::critical(0, qApp->tr("Cannot open database"), "Click Cancel to exit.", QMessageBox::Cancel); return false; } QSqlQuery query; qDebug() << "table:" << query.exec("create table person (id int primary key, " "firstname varchar(20), lastname varchar(20), num int )"); query.exec("insert into person (firstname , lastname, num) values('Dennis', 'Young','1')"); query.exec("insert into person values(102, 'Christine', 'Holand','2')"); query.exec("insert into person values(103, 'Lars junior', 'Gordon','4')"); query.exec("insert into person values(104, 'Roberto', 'Robitaille','5')"); query.exec("insert into person values(105, 'Maria', 'Papadopoulos','3')"); return true; }
later we can just do
void ProcessDB() { QSqlQuery query; bool ok = query.prepare("SELECT * from person "); query.exec(); while (query.next()) { QString name = query.value(2).toString(); // col 1 = name qDebug() << ">" << name; } }
and QSqlQuery uses the default database we open in the other function.
so there is no need to transfer the DB instance around.
However, i can highly recommend hiding all QSqlQuery related stuff in a class so
the whole program does not have to know how it's stored in the database. -
@mrjj Thanks for such a fast answer!
So, you mean, I should better create a conenction class, paste there all the connection code like the first part from your post and in other class just use QSqlQuery and it will connect to the same database without any extra code? -
@PaulWWW
Hi
Well you should just open the database somewhere at startup and you can use
QSqlQuery ( and it will indirectly use that default connection ) you have opened, from
anywhere else in the project. and Yes, no extra code needed as long as you just use one database for whole
app. ( a database can contain multiple tables etc so normally no need for multiple database files) -
@PaulWWW
Most welcome.
Please note Qt have models for databases.
https://doc.qt.io/qt-5/sql-model.html
So say editing a full table can be done with Qt predefined class and no extra code so make sure
you look into those to avoid manually updates when not really needed.