0

This won't work:

{
    QSqlDatabase db;
    db.addDatabase("QSQLITE", "manDb");
    QString path = QDir::currentPath()+"/"+"Sqlite.db";
    db.setDatabaseName(path);
    if(db.open())
    {
        qDebug()<< "Database Created successfully...";

    }else{
        qDebug()<< "Failed to create Database...";
    }
}
QSqlDatabase::removeDatabase("manDb");

Output: Failed to create Database...

But this works:

{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "manDb");
    QString path = QDir::currentPath()+"/"+"Sqlite.db";
    db.setDatabaseName(path);
    if(db.open())
    {
        qDebug()<< "Database Created successfully...";

    }else{
        qDebug()<< "sucessfully Failed to create Database...";
    }
}
QSqlDatabase::removeDatabase("manDb");

Output: Database Created successfully...

Why?

yssh
  • 29
  • 5

1 Answers1

0

Your first code sample does not work because according to documentation QSqlDatabase db;

Creates an empty, invalid QSqlDatabase object. Use addDatabase(), removeDatabase(), and database() to get valid QSqlDatabase objects.

Then you try to call static QSqlDatabase::addDatabase method with db.addDatabase("QSQLITE", "manDb"); which returns QSqlDatabase class instance, but you do not assign it's return value to variable to use it later.

Adds a database to the list of database connections using the driver type and the connection name connectionName. If there already exists a database connection called connectionName, that connection is removed.

The database connection is referred to by connectionName. The newly added database connection is returned.

So, in the first sample you tried to use QSqlDatabase in wrong way. Meanhile your second sample is a correct usage.

Alexey
  • 2,439
  • 1
  • 11
  • 15