qt/SQLite

这里主要是针对sqlite的

首先到sqlite官方网站下载:

http://www.sqlite.org/download.html


得到sqlite3.exe。即可.就可以操作数据库,不用安装,不会修改系统信息。

我们在DOS下运行sqlite3.exe的目录运行sqlite3.exe test就可以创建一个名为test的数据库

下面我们就可以创建数据库的表了如:

create table student(id varchar(10),name varchar(20),age smallint);

注意sqlite命令是基于sql的,必须在命令后面加上“;”,否则sqlite会认为一条语句还没有输入完成,总会提示用户输入。

insert into student values('1001','lovesizhao',26);//增加数据库内容

select * from student;//查看student数据库表的所有内容。这个时候会在sqlite3.exe目录得到一个名为test的文件,就是刚刚生成数据库文件

当然这是在DOS操作,我将DOS下操作得到的数据库文件test放到Qt工程目录,在QT控制台程序中读取操作,但是却不能显示中文,不知道为什么。后来改成直接都在QT程序中增加数据库内容,也出现中文乱码,在网上找到答案:

将QT设置编码的地方改为:QTextCodec::setCodecForTr(QTextCodec::codecForLocale()));设置为本地编码,插入数据时对查询语句进行QObject::tr()

(首先应该在.pro文件增加一句:QT += sql)

如下源码:

#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,'李刚')"));
    query.exec(QObject::tr("insert into student values(2,'苹果')"));
    query.exec(QObject::tr("insert into student values(3,'葡萄')"));
    query.exec(QObject::tr("insert into student values(3,'李子')"));
    query.exec(QObject::tr("insert into student values(4,’橘子')"));
    query.exec(QObject::tr("insert into student values(5,'核桃')"));
    query.exec(QObject::tr("insert into student values(6,'芒果')"));
    //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();
}

(清悠我心:http://hi.baidu.com/清悠我心/home)

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能