Qt連接SQL Server數據庫

前提:
SQL Server裏已經建立了相應的數據庫,有對應的表和數據。

步驟:
1. Qt裏新建一個空工程,添加main.cpp文件。
2. 在工程文件(.pro文件)添加一行:QT += sql。
3. 該敲代碼了,代碼如下:

#include <QtGui>
#include <QString>
#include <QTextCodec>
#include <QSqlDatabase>
#include <QtSql>

/*連接數據庫*/
void OpenDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setDatabaseName(QString("DRIVER={SQL SERVER};"
                               "SERVER=%1;"
                               "DATABASE=%2;"
                               "UID=%3;"
                               "PWD=%4;").arg("QIAN-PC")
                       .arg("StuManager")
                       .arg("sa")
                       .arg("123456"));
    if (!db.open())
    {

        QMessageBox::warning(0, qApp->tr("Cannot open database"),
                db.lastError().databaseText(), QMessageBox::Cancel);
    }
    else
    {
        qDebug()<<"Connect to Database Success!";
    }

}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    /*設置編碼格式*/
    QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));

    OpenDatabase();

    QDialog *mainDialog = new QDialog;
    QTableView *tableView = new QTableView;
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(tableView);
    mainDialog->setLayout(layout);

    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery(QObject::tr("select * from 教師"));
    tableView->setModel(model);

    mainDialog->adjustSize();
    mainDialog->show();

    return a.exec();
}

4. 看看運行結果吧。

 

參考網址:http://hhuayuan.blog.51cto.com/1630327/893415

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章