五十九、Qt之连接 sql server 2008数据库

void Dialog::initDatabase()
{
    //连接 sql server 数据库
    conn = QSqlDatabase::addDatabase("QODBC");
    conn.setDatabaseName(QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;")
                         .arg(App::DB_HOSTNAME)
                         .arg(App::DB_DATABASE_NAME));
    conn.setUserName(App::DB_USERNAME);
    conn.setPassword(App::DB_PASSWORD);
    conn.setPort(App::DB_PORT);

    if (!conn.open()) {
        QMessageBox::critical(this, tr("数据库连接失败"), conn.lastError().text());
    } else {
        initTable();
        qDebug() << "数据库连接成功!";
    }
}

你可能感兴趣的:(QT)