Qt中MySQL數(shù)據(jù)庫編程課件_第1頁
Qt中MySQL數(shù)據(jù)庫編程課件_第2頁
Qt中MySQL數(shù)據(jù)庫編程課件_第3頁
Qt中MySQL數(shù)據(jù)庫編程課件_第4頁
Qt中MySQL數(shù)據(jù)庫編程課件_第5頁
已閱讀5頁,還剩15頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、Qt中MySQL數(shù)據(jù)庫編程Qt使用SQL 主要是下面的幾個類 QSqlDatabase 建立于數(shù)據(jù)庫的鏈接 QSqlQuery 用于執(zhí)行SQL語句 QSqlTableModel 結(jié)合QTableView可以輸出數(shù)據(jù)庫的表貼下我寫的簡單Demo   cpp view plaincopyprint?1. QSqlDatabase db =QSqlDatabase:addDatabase("QMYSQL"); / becomes the new def

2、ault connection   2.     db.setUserName("root");/用戶名   3.     db.setPassword("password");/密碼   4.     db.setHostName("localhost");  5.     db.set

3、DatabaseName("test");/數(shù)據(jù)庫名   6.     db.setConnectOptions("CLIENT_SSL=1;CLIENT_IGNORE_SPACE=1");/使用SSL   7.     db.setPort(3306);/端口   8.     if(db.open()  9.    

4、0;    qDebug()<<"open/n"<<db.lastError().driverText()<<"/n"  10.       11.     else  12.         qDebug()<<"open fai

5、le/n"  13.       14.     QSqlQuery query;/用于執(zhí)行SQL語言   15.      query.exec("show databases");/很方便的   16.      while (query.next()  

6、 17.          qDebug()<<query.value(0).toString()<<"/n"  18.   19.       20.   21.     QSqlTableModel *model = new QSqlTableMode

7、l;/間接將數(shù)據(jù)庫表裝入QTableView   22.     model->setTable("people");   /表名   23.     model->setEditStrategy(QSqlTableModel:OnManualSubmit);  24.     model->select();  25. 

8、0;   /model->removeColumn(0); / don't show the ID   26.     /model->setHeaderData(0, Qt:Horizontal, QObject:tr("ID");   27.     model->setHeaderData(0, Qt:Horizon

9、tal, tr("Name");  28.     model->setHeaderData(1, Qt:Horizontal, tr("Age");  29.     model->setHeaderData(2, Qt:Horizontal, tr("Sex");  30.   31.   3

10、2.     QTableView *view = new QTableView(this);  33.     view->setModel(model);  34.   35.     db.close();  36.   37.     QGridLayout * g

11、l=new QGridLayout();  38.     gl->addWidget(view);  39.     this->setLayout(gl);  2、 下面是最終的現(xiàn)實效果如下:現(xiàn)在先做一個顯示的界面,界面是由一個表格試圖和三個按鈕組成。我的大概流程是: <1>在對話框窗口先創(chuàng)建一個柵格布局管理器,添加一個表格視圖窗口部件。<2>創(chuàng)建一個水平布局管理器,在水平布局管理器中添加三個按鈕

12、,最后將水平布局管理器添加到柵格布局管理器中。<3>創(chuàng)建三個按鈕的信號與槽<4>數(shù)據(jù)庫的使用分為三步:(1)QsqlDatabase建立數(shù)據(jù)庫的鏈接(2)QsqlQuery用于執(zhí)行SQL語句(3)QsqlTableModel結(jié)合QtableView可以輸出數(shù)據(jù)庫的表。<5>效果測試點擊connect按鈕鏈接打開數(shù)據(jù)庫 #include#include "table.h" int main(int argc,char *argv) QApplication app(argc,argv); Table *table = new Ta

13、ble; table->show(); return app.exec();#ifndef TABLE_H#define TABLE_H #include#includeclass QGridLayout;class QPushButton;class QHBoxLayout;class Table:public QDialog Q_OBJECT public: /繼承公共對話框窗體派生類 Table(QWidget *parent = 0); /創(chuàng)建各個類的指針 QTableView *table; QGridLayout *gridLayout; QPushButton *conne

14、ctButton; QPushButton *executionButton; QPushButton *displayButton; QHBoxLayout *verticalLayout; private slots:/創(chuàng)建三個按鈕槽函數(shù) void on_connectButton_clicked(); void on_executionButton_clicked(); void on_displayButton_clicked(); ; #endif#include#include#include#include#include "table.h" Table:Ta

15、ble(QWidget *parent) :QDialog(parent)/創(chuàng)建視圖及按鈕的對象 table = new QTableView; connectButton = new QPushButton("connect"); executionButton = new QPushButton("execution"); displayButton = new QPushButton("display");/建立三個信號與槽函數(shù)鏈接 connect(connectButton,SIGNAL(clicked(),this,SLOT

16、(on_connectButton_clicked();  connect(executionButton,SIGNAL(clicked(),this,SLOT(on_executionButton_clicked(); connect(displayButton,SIGNAL(clicked(),this,SLOT(on_displayButton_clicked();/創(chuàng)建一個水平布局管理器,布局三個按鈕 verticalLayout = new QHBoxLayout; verticalLayout->addWidget(connectButton); verticalL

17、ayout->addWidget(executionButton); verticalLayout->addWidget(displayButton);/創(chuàng)建一個柵格布局管理器對整體窗口部件的排布。 gridLayout = new QGridLayout; gridLayout->addWidget(table,0,0,1,1); gridLayout->addLayout(verticalLayout,1,0,1,1); setLayout(gridLayout);/設(shè)置窗口的大小 resize(500,400); void Table:on_connectButt

18、on_clicked()/鏈接函數(shù)實現(xiàn)數(shù)據(jù)庫的鏈接功能 QSqlDatabase db = QSqlDatabase:addDatabase("QMYSQL"); /添加QMYSQL數(shù)據(jù)庫驅(qū)動 db.setHostName("localhost"); /設(shè)置登陸的主機名為localhost db.setUserName("root"); /登陸的用戶是超級用戶 root db.setPassword("123456"); /登陸密碼是123456 db.setDatabaseName("student&q

19、uot;); /打開的數(shù)據(jù)庫表格,這個表格式預(yù)先創(chuàng)建好的。用>create database student;創(chuàng)建。 bool ok = db.open();/布爾類型,打開數(shù)據(jù)。 if(ok) /if判斷 qDebug()<<"open Database!"<<endl;/如果打開數(shù)據(jù)庫在終端輸出open Database信息 else QMessageBox:critical(0,QObject:tr("Database Error"),db.lastError().text(); /否則輸出數(shù)據(jù)庫的消息框錯誤信息 vo

20、id Table:on_executionButton_clicked() /按executionButton按鈕執(zhí)行SQL語句 QSqlQuery query; /創(chuàng)建一個執(zhí)行數(shù)據(jù)庫SQL語句對象 query.exec("drop table employee");/如果存在employee數(shù)據(jù)庫表格,先刪除 query.exec("create table employee(id int(11) primary key,name varchar(50),description varchar(255)");/在創(chuàng)建數(shù)據(jù)庫表格employee quer

21、y.exec("insert into employee values(1,'zhangsan','student')"); query.exec("insert into employee values(2,'lisi','teacher')"); query.exec("insert into employee values(3,'wangwu','professor')"); /插入三個記錄 void Table:on_display

22、Button_clicked() /用數(shù)據(jù)庫表格模式結(jié)合試圖顯示數(shù)據(jù)庫內(nèi)容。 QSqlTableModel *model = new QSqlTableModel; /創(chuàng)建數(shù)據(jù)表模式對象 model->setTable("employee"); /設(shè)置數(shù)據(jù)庫表上的運作模式以employee表名,不選擇從數(shù)據(jù)表格以外獲取信息 model->setEditStrategy(QSqlTableModel:OnManualSubmit); /所有更改將被緩存在模型中,直到submitAll()或revertAll()函數(shù)被調(diào)用 model->select();/s

23、elect()函數(shù)用于確定一個或多個套接口的狀態(tài)。對每一個套接口,調(diào)用者可查詢它的可讀性、可寫性及錯誤狀態(tài)信息。 model->setHeaderData(0,Qt:Horizontal,QObject:tr("ID"); model->setHeaderData(1,Qt:Horizontal,QObject:tr("name"); model->setHeaderData(2,Qt:Horizontal,QObject:tr("description"); /對應(yīng)指定的字段并設(shè)置對應(yīng)的水平標(biāo)題顯示 table-&

24、gt;setModel(model); /將這個數(shù)據(jù)庫表格模式用視圖顯示出來。  在關(guān)閉對話框后出現(xiàn)查詢應(yīng)用默認數(shù)據(jù)庫連接錯誤:QSqlDatabasePrivate:removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.我googel以下,參照的內(nèi)容測試,還是解決不了。在第二個按鈕末尾添加下面的語句:QString name;        nam

25、e = QSqlDatabase:database().connectionName();QSqlDatabase:removeDatabase(name);On_executionButton_clicked()函數(shù)末尾添加,執(zhí)行SQL語句后關(guān)閉窗口時有效的,但在on_displayButton_clicked()函數(shù)末尾添加卻沒有效。問題還在解決當(dāng)中。Qt中MySQL數(shù)據(jù)庫操作首先,要查詢相關(guān)的驅(qū)動是否已經(jīng)裝好了,可以用以下的程序進行驗證:#include <QtCore/QCoreApplication>#include <QSqlDatabase>#includ

26、e <QDebug>#include <QStringList>int main(int argc, char *argv)    QCoreApplication a(argc, argv);    qDebug()<<"Available drivers:"    QStringList drivers = QSqlDatabase:drivers();    foreach(QString driver, driv

27、ers)     qDebug() <<"/t" << driver;    return a.exec(); 結(jié)果如下: 接著是連接數(shù)據(jù)庫:#include <QtGui/QApplication>#include <QtGui>#include <QtSql>bool createConnection()    QSqlDatabase db = QSqlDatabase:addDatabas

28、e("QMYSQL");    db.setDatabaseName("test");    db.setUserName("root");    db.setPassword("123456");    bool ok = db.open();    if(!ok)        QMessage

29、Box:critical(0, QObject:tr(" 連接數(shù)據(jù)庫失?。?"), db.lastError().text();        return false;    else        QMessageBox:information(0, QObject:tr("Tips"), QObject:tr(" 連接數(shù)據(jù)庫成功! ");  

30、      return true;    int main(int argc, char *argv)    QApplication a(argc, argv);    QTextCodec *codec= QTextCodec:codecForName("GB2312");    QTextCodec:setCodecForLocale(codec);    QTextC

31、odec:setCodecForCStrings(codec);    QTextCodec:setCodecForTr(codec);    if(!createConnection()        return 1;    return a.exec(); 插入操作:/ODBC 數(shù)據(jù)庫表示方式QSqlQuery query;query.prepare( “insert into student (id, name) ”&

32、#160;                 “values (:id, :name) ”);query.bindValue(0, 5);query.bindValue(1, “sixth ”);query.exec();  /Oracle 表示方式query.prepare( “insert into student (id, name) ”      &#

33、160;           “values (?, ?) ”);query.bindValue(0, 5);query.bindValue(1, “sixth ”);query.exec(); / 使用 addBindValue() 函數(shù),省去了編號,它是按屬性順序賦值的query.prepare( “insert into student (id, name) ”          

34、        “values (?, ?) ”);query.addBindValue(5);query.addBindValue( “sixth ”);query.exec(); / 使用 ODBC 方法時,可以將編號用實際的占位符代替query.prepare( “insert into student (id, name) ”               &#

35、160;      “values (:id, :name) ”);query.bindValue( “:id ”, 5);query.bindValue( “:name ”, “sixth ”);query.exec();注意:最后一定要執(zhí)行 exec() ,否則上面的語句是不會被執(zhí)行的。  / 進行多個記錄的插入時,可以利用綁定進行批處理QSqlQuery q;q.prepare( “insert into student values (?, ?) ”);QVariantList ints;ints <<

36、10 << 11 << 12 << 13;q.addBindValue(ints);QVariantList names;names << “xiaoming ” << “xiaoliang ” << “xiaogang ” << QVariant(QVariant:String);/ 最后一個是空字符串,應(yīng)與前面的格式相同q.addBindValue(names);if (!q.execBatch() / 進行批處理,如果出錯就輸出錯誤      &

37、#160; qDebug() << q.lastError(); 查詢操作: / 返回全部的屬性和結(jié)果集 QSqlQuery query;query.exec( “select * from student ”);/ 執(zhí)行查詢操作qDebug() << “exec next() : ”;if(query.next()/ 開始就先執(zhí)行一次next() 函數(shù),那么query 指向結(jié)果集的第一條記錄        int rowNum = query.at(); &#

38、160;      / 獲取query 所指向的記錄在結(jié)果集中的編號        int columnNum = query.record().count();        / 獲取每條記錄中屬性(即列)的個數(shù)        int fieldNo = query.record().indexOf( “name ”); &#

39、160;      / 獲取 ” name ”屬性所在列的編號,列從左向右編號,最左邊的編號為 0        int id = query.value(0).toInt();        / 獲取id 屬性的值,并轉(zhuǎn)換為int 型       QString name = query.value(fieldNo).toString();

40、60;       / 獲取name 屬性的值        qDebug() << “rowNum is : ” << rowNum / 將結(jié)果輸出                << ” id is : ” << id    &

41、#160;           << ” name is : ” << name                << ” columnNum is : ” << columnNum;qDebug() << “exec seek(2) : ”;if(query.seek(2)/ 定位到結(jié)果集

42、中編號為2 的記錄,即第三條記錄,因為第一條記錄的編號為 0        qDebug() << “rowNum is : ” << query.at()                << ” id is : ” << query.value(0).toInt()     &#

43、160;          << ” name is : ” << query.value(1).toString();qDebug() << “exec last() : ”;if(query.last()/ 定位到結(jié)果集中最后一條記錄        qDebug() << “rowNum is : ” << query.at()    

44、;            << ” id is : ” << query.value(0).toInt()                << ” name is : ” << query.value(1).toString(); 結(jié)果集其實就是查詢到的所有記錄的集合,而在QSql

45、Query 類中提供了多個函數(shù)來操作這個集合,需要注意這個集合中的記錄是從 0 開始編號的。最常用的有:seek(int n) :query 指向結(jié)果集的第n 條記錄。first() :query 指向結(jié)果集的第一條記錄。last() :query 指向結(jié)果集的最后一條記錄。next() :query 指向下一條記錄,每執(zhí)行一次該函數(shù),便指向相鄰的下一條記錄。previous() :query 指向上一條記錄,每執(zhí)行一次該函數(shù),便指向相鄰的上一條記錄。record() :獲得現(xiàn)在指向的記錄。value(int n) :獲得屬性的值。其中n 表示你查詢的第n 個屬性,比方上面我們使用 “ sel

46、ect * from student ”就相當(dāng)于 “ select id, name from student ”,那么value(0) 返回id 屬性的值,value(1) 返回name 屬性的值。該函數(shù)返回QVariant 類型的數(shù)據(jù),關(guān)于該類型與其他類型的對應(yīng)關(guān)系,可以在幫助中查看QVariant 。at() :獲得現(xiàn)在query 指向的記錄在結(jié)果集中的編號。需要說明,當(dāng)剛執(zhí)行完query.exec( “select * from student ”); 這行代碼時,query 是指向結(jié)果集以外的,我們可以利用query.next() ,當(dāng)?shù)谝淮螆?zhí)行這句代碼時,query 便指向了結(jié)果集

47、的第一條記錄。當(dāng)然我們也可以利用seek(0) 函數(shù)或者first() 函數(shù)使query 指向結(jié)果集的第一條記錄。但是為了節(jié)省內(nèi)存開銷,推薦的方法是,在query.exec( “select * from student ”); 這行代碼前加上query.setForwardOnly(true); 這條代碼,此后只能使用next() 和seek() 函數(shù)。  / 滿足一定條件的結(jié)果集,方法一 QSqlQuery query;query.prepare( “select name from student where id = ? ”);int id =2; / 從

48、界面獲取id 的值query.addBindValue(id); / 將id 值進行綁定query.exec();query.next(); / 指向第一條記錄qDebug() << query.value(0).toString(); / 方法二QSqlQuery query;query. exec( QObject : tr( "select * from student where id = %1" ). arg( 2 );if (! query. next()       

49、qDebug()<< "none" ;else        qDebug()<< query. value( 0 ). toInt()<< query. value( 1 ). toString(); 事務(wù)是數(shù)據(jù)庫的一個重要功能,所謂事務(wù)是用戶定義的一個數(shù)據(jù)庫操作序列,這些操作要么全做要么全不做,是一個不可分割的工作單位。在Qt 中用transaction() 開始一個事務(wù)操作,用commit() 函數(shù)或rollback() 函數(shù)進行結(jié)束。commit()

50、表示提交,即提交事務(wù)的所有操作。具體地說就是將事務(wù)中所有對數(shù)據(jù)庫的更新寫回到數(shù)據(jù)庫,事務(wù)正常結(jié)束。rollback() 表示回滾,即在事務(wù)運行的過程中發(fā)生了某種故障,事務(wù)不能繼續(xù)進行,系統(tǒng)將事務(wù)中對數(shù)據(jù)庫的所有已完成的操作全部撤銷,回滾到事務(wù)開始時的狀態(tài)。QSqlQuery query;if(QSqlDatabase:database().transaction() / 啟動事務(wù)操作         / 下面執(zhí)行各種數(shù)據(jù)庫操作       

51、60;    query.exec( “insert into student values (14, hello) ”);      query.exec( “delete from student where id = 1 );            /            if(!QSqlD

52、atabase:database().commit()                      qDebug() << QSqlDatabase:database().lastError(); / 提交              

53、60;          if(!QSqlDatabase:database().rollback()                    qDebug() << QSqlDatabase:database().lastError(); / 回滾      

54、0;     / 輸出整張表query.exec( “select * from student ”);while(query.next()     qDebug() << query.value(0).toInt() << query.value(1).toString();Qt 中使用了自己的機制來避免使用SQL 語句,它為我們提供了更簡單的數(shù)據(jù)庫操作和數(shù)據(jù)顯示模型。它們分別是只讀的QSqlQueryModel ,操作單表的QSqlTableModel 和以及可以支持外鍵的QS

55、qlRelationalTableModel / QSqlQueryModelQSqlQueryModel *model = new QSqlQueryModel;model->setQuery( “select * from student ”);model->setHeaderData(0, Qt:Horizontal, tr( “id ”);model->setHeaderData(1, Qt:Horizontal, tr( “name ”);QTableView *view = new QTableView;view->setModel(model);

56、view->show();/QSqlTableModelQSqlTableModel *model;model = new QSqlTableModel(this);model->setTable( “student ”);model->setEditStrategy(QSqlTableModel:OnManualSubmit);model->select(); / 選取整個表的所有行/ model->removeColumn(1); / 不顯示name 屬性列 , 如果這時添加記錄,則該屬性的值添加不上ui->tableView->setModel(

57、model);/ ui->tableView->setEditTriggers(QAbstractItemView:NoEditTriggers);   / 使其不可編輯/ 過濾model->setFilter(QObject:tr(“name = %1 ”).arg(name); / 根據(jù)姓名進行篩選model->select(); / 顯示結(jié)果/ 刪除操作int curRow = ui->tableView->currentIndex().row();    / 獲取選中的行model->remov

58、eRow(curRow);    / 刪除該行int ok = QMessageBox:warning(this,tr( “刪除當(dāng)前行! ”),tr( “你確定 ”                                                           “刪除當(dāng)前行嗎? ” ),

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論