加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

QT 操作 sqlite数据库(一)-----网络常规代码

发布时间:2020-12-12 20:42:38 所属栏目:百科 来源:网络整理
导读:首先说明参考了网络上的一个常规的代码,但实际使用中遇到不少的问题,先把常规使用方式粘贴如下: #include QtCore/QCoreApplication #include QtSql #include QTextCodec int main(int argc,char *argv[]){ QCoreApplication a(argc,argv); QTextCodec::se

首先说明参考了网络上的一个常规的代码,但实际使用中遇到不少的问题,先把常规使用方式粘贴如下:

#include <QtCore/QCoreApplication>  
#include <QtSql> 
#include <QTextCodec> 
int main(int argc,char *argv[])
{      
    QCoreApplication a(argc,argv);     
    QTextCodec::setCodecForTr(QTextCodec::codecForLocale());       
    QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE");    //添加数据库驱动        
    dbconn.setDatabaseName("mytest.db");  //在工程目录新建一个mytest.db的文件        
    if(!dbconn.open())    
    {            
        qDebug()<<"fdsfds";       
    }       
    QSqlQuery query;//以下执行相关QSL语句       
    query.exec("create table student(id varchar,name varchar)");    //新建student表,id设置为主键,还有一个name项       
    query.exec(QObject::tr("insert into student values(1,'aaa')"));        
    query.exec(QObject::tr("insert into student values(2,'bbb')"));        
    query.exec(QObject::tr("insert into student values(3,'ccc')"));         
    query.exec(QObject::tr("insert into student values(3,'ddd')"));         
    query.exec(QObject::tr("insert into student values(4,'eee')"));         
    query.exec(QObject::tr("insert into student values(5,'fff')"));         
    query.exec(QObject::tr("insert into student values(6,'ggg')"));        
    query.exec(QObject::tr("select id,name from student where id>=1"));         
    query.exec("select id,name from student where id>=1");         
    while(query.next())//query.next()指向查找到的第一条记录,然后每次后移一条记录    
    {              
        int ele0=query.value(0).toInt();//query.value(0)是id的值,将其转换为int型                     
        QString ele1=query.value(1).toString();                     
        qDebug()<<ele0<<ele1;//输出两个值    
    }      
    query.exec(QObject::tr("drop student"));       
    return a.exec();  
} 
如上的方式不是好,只是在使用过程中有很多不便的地方,会遇到不少的问题,我会在下面的小节中修改这个思路,然后按照一般软件开发的方式进行重新实现。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读