本文的环境是:Win 64位系统 + Qt5.9 Creator版本 + C++语言开发
文本主要总结了用Qt5.9读取SQLlit数据库内容,具体的内容如下所述。
1.1新建一个Qt的Console工程,在.pro工程下,添加如下代码:
QT+=sql
1.2主程序main.cpp的代码如下所示:
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc,argv);
//创建一个SQLite数据连接
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
//数据库连接命名
db.setDatabaseName(":memory:");
//打开数据库
if(!db.open()) return false;
//以下执行相关sql语句
QSqlQuery query;
//新建student表,id设置为主键,还有一个name项
query.exec("createtablestudents(idintprimarykey,namevarchar)");
//向表中插入3条记录
query.exec("insert into students values(1,'zhangsan')");
query.exec("insert into students values(2,'lisi')");
query.exec("insert into students values(3,'wangwu')");
//查找表中id>=2的记录的id项和name项的值
query.exec("selectid,name from students where id >= 2");//"selectid,name from students"遍历students表内容
//query.next()指向查找到的第一条记录,然后每次后移一条记录
while(query.next())
{
//query.value(0)是id的值,将其转换为int型
int value0 = query.value(0).toInt();//QVariant转int
QString value1 = query.value(1).toString();//QVariant转QString
//输出两个值
qDebug()<<value0<<value1;
}
return a.exec();
}
1.3程序构建和运行后,结果如下图所示:
参考内容:
http://www.qter.org/portal.php?mod=view&aid=51