Qt 数据库操作(一)
Qt 中的數(shù)據(jù)庫(kù)操作比較簡(jiǎn)單,因?yàn)镼t提供了不需要SQL知識(shí)就可以瀏覽和編輯數(shù)據(jù)庫(kù)的接口。
Qt中的Qtsql模塊提供了對(duì)數(shù)據(jù)庫(kù)的支持,該模塊中的眾多類基本可以分為3層:
- 用戶接口層: QSqlQueryModel,QSqlTableModel 和 QSqlRelationalTableModel
- SQL接口層:QSqlDatabase、QSqlQuery,QSqlError、QSqlField、QSqlIndex
和QSqlRecord - 驅(qū)動(dòng)層: QSqlDriver ,QSqlDriverCreator< T >,QSqlDriverCreatorBase,QSqlDriverPlugin 和 QSqlResult
驅(qū)動(dòng)層為具體的數(shù)據(jù)庫(kù)和SQL接口層之間提供了底層的橋梁;
SQL接口層提供了對(duì)數(shù)據(jù)的訪問(wèn),其中QSqlDatabase類用來(lái)創(chuàng)建連接,QSqlQuery類可以使用SQL語(yǔ)句來(lái)實(shí)現(xiàn)與數(shù)據(jù)庫(kù)的交互;
用戶接口層的類實(shí)現(xiàn)了將數(shù)據(jù)庫(kù)鏈接到窗口部件上,這些類是使用模型、視圖框架實(shí)現(xiàn)的。
如果要使用QtSql模塊中的類,需要在項(xiàng)目文件(.pro)中添加“”“QT+=sql”;
執(zhí)行如下代碼:
qDebug() << "Available drivers:";QStringList drivers = QSqlDatabase::drivers();foreach(QString driver, drivers)qDebug() << driver;輸出:
Available drivers:
“QSQLITE”
“QODBC”
“QODBC3”
“QPSQL”
“QPSQL7”
可以發(fā)現(xiàn)Qt 默認(rèn)并不支持mysql 的驅(qū)動(dòng)。不過(guò)可以手動(dòng)添加mysql 的驅(qū)動(dòng)文件。這里先不作重點(diǎn)介紹了。
這里我們先就SQLite數(shù)據(jù)庫(kù),它是一款輕型的文件型數(shù)據(jù)庫(kù),主要用在嵌入式領(lǐng)域,支持跨平臺(tái)。
1、創(chuàng)建數(shù)據(jù)庫(kù)鏈接
QSqlDataBase db = QSqlDataBase :: addDataBase("QSQLITE");//以默認(rèn)方式,創(chuàng)建連接對(duì)象 //初始化數(shù)據(jù)庫(kù)信息 db.setHostName("bigblue"); //設(shè)置主機(jī)名 db.setDatabaseName("fightdb"); //設(shè)置數(shù)據(jù)庫(kù)名 db.setUserName("myname"); //設(shè)置用戶名 db.setPassword("lusfasdf"); //設(shè)置密碼 bool ok = db.open(); //打開數(shù)據(jù)庫(kù)2、SQLite數(shù)據(jù)庫(kù)的建立
先創(chuàng)建connection.h 文件,
#ifndef CONNECTION_H #define CONNECTION_H #include <QMessageBox> #include <QSqlDatabase> #include <QSqlQuery>static bool createConnection() {QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");db.setDatabaseName(":memory:");if (!db.open()) {QMessageBox::critical(0, "Cannot open database","Unable to establish a database connection.", QMessageBox::Cancel);return false;}QSqlQuery query;query.exec("create table student (id int primary key, ""name varchar(20))");query.exec("insert into student values(0, 'LiMing')");query.exec("insert into student values(1, 'LiuTao')");query.exec("insert into student values(2, 'WangHong')");return true; }#endif // CONNECTION_H創(chuàng)建連接并插入數(shù)據(jù)表項(xiàng)
然后在主函數(shù)調(diào)用并查詢數(shù)據(jù)庫(kù)。
#include <QApplication> #include <QSqlDatabase> #include <QDebug> #include <QStringList> #include "connection.h" #include <QVariant>int main(int argc, char *argv[]) {QApplication a(argc, argv);// 創(chuàng)建數(shù)據(jù)庫(kù)連接if (!createConnection()) return 1;// 使用QSqlQuery查詢整張表QSqlQuery query;query.exec("select * from student");while(query.next()){qDebug() << query.value(0).toInt() << query.value(1).toString();}return a.exec(); }總結(jié)
以上是生活随笔為你收集整理的Qt 数据库操作(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Qt 项目视图的便捷类
- 下一篇: 基于笛卡尔坐标系下的三边定位的研究(TO