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

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