数据库几乎是每个较大的软件所必须应用的,而在Qt中也使用QtSql模块实现了对数据库的完美支持。我们可以在Qt Creator的帮助中查找QtSql Module的帮助文档。

这个模块是一组类的集合,使用这个模块我们需要加入头文件#include<QtSql>并且在工程文件中需要加入一行代码:QT += sql

直接上源代码给大家看:

#include <QtCore/QCoreApplication>
#include <QtSql>

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

    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if(!db.open())
    {
        return false;
    }
    QSqlQuery query;
    query.exec("create table student (id int primary key,name varchar)");
    query.exec("insert into student values(1,'xiaogang')");
    query.exec("insert into student values(2,'xiaohua')");
    query.exec("insert into student values(3,'xiaoming')");
    query.exec("select id,name from student where id>=2");
    while(query.next())
    {
        int ele0 = query.value(0).toInt();
        QString ele1 = query.value(1).toString();
        qDebug()<<ele0<<ele1;
    }
    return a.exec();
}


 

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐