Qt World Summit: Register Today!

What does it mean to clone database connection?

  • I have some code that looks like this that establishes connection to postgresql database:
    QSqlDatabase db;
    QString new_name;

    for (int i = 0; i < 50; i++) {
      new_name = Qstring("%1_%2").arg(db_name).arg(i); 
      if (!QSqlDatabase::contains(new_name)) {
        if (i > 0) {
          QString previous = QString("%1_%2").arg(db_name).arg(i - 1);

    Log::write(QString("Cloning existing DB connection "%1" as "%2"...\n").arg(previous).arg(new_name));
    db = QSqlDatabase::cloneDatabase(db, previous);

    m_db_connection = new_name;
    if (!db.isValid()) {
      db = QSqlDatabase::addDatabase("QPSQL", new_name);
    if (db.open()) {

    The QSqlDatabase class represents a connection to a database. The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers.

    The cloneDatabase method clones the database connection other and stores it as connectionName. All the settings from the original database, e.g. databaseName(), hostName(), etc., are copied across. Does nothing if other is an invalid database. Returns the newly created database connection.

    What does it mean to clone database connection and why would someone want to clone 50 database connections?

  • Lifetime Qt Champion


    In short it's creating a new connection using the same set of parameters with a different name so you can use it from a different thread and avoid having to set all the parameters again.

    This code doesn't clone the connection 50 times, It clones it once he can find an "available" name with a parameter up to 50. But there are other flaws in it so if you can, I would recommend to analyze what this code should do (e.g. the function/object purpose) and refactor it to do it right.

Log in to reply