Jackey
Jackey

Reputation: 75

How to check a mysql database is exists with Qt?

When I remote connect a mysql server, I need to check whether a mysql database file named like "TestMySQL" exists. What do I need to do with Qt?

Upvotes: 0

Views: 271

Answers (1)

mugiseyebrows
mugiseyebrows

Reputation: 4708

QMYSQL driver reports error "Unknown database 'TestMySQL' QMYSQL: Unable to connect" in that case

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1");
db.setUserName("user1");
db.setPassword("********");
db.setDatabaseName("TestMySQL");

if (!db.open()) {
    QString text = db.lastError().text();
    qDebug() << text;
    if (text.contains("Access denied for user", Qt::CaseInsensitive)) {
        qDebug() << "Access denied";
    } else if (text.contains("Unknown database", Qt::CaseInsensitive)) {
        qDebug() << "Database" << db.databaseName() << "does not exist";
    } else {
        qDebug() << "Other error" << text;
    }
}

Upvotes: 1

Related Questions