前端之家收集整理的这篇文章主要介绍了
QT操作Sqlite数据库,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#include <QtCore/QCoreApplication>
#include <QtCore>
#include <QApplication>
#include <QTextCodec>
#include <QsqlDatabase>
#include <QMessageBox>
#include <QsqlQuery>
#include <QTime>
#include <QsqlError>
#include <QtDebug>
#include <QsqlDriver>
#include <QsqlRecord>
#include <stdio.h>
int main(int argc,char *argv[])
{
QCoreApplication a(argc,argv);
QTextCodec::setCodecForTr(QTextCodec::codecForLocale());
QsqlDatabase db=QsqlDatabase::addDatabase("QsqlITE");
db.setDatabaseName("test.db");
if(!db.open())
{
QMessageBox::critical(0,QObject::tr("无法打开数据库,请检查驱动"),QObject::tr("出错了"),QMessageBox::Ok);
return -1;
}
QsqlQuery query;
query.exec("drop table if exists mobile");
bool success=query.exec("create table mobile"
"(id int primary key,"
"attribute varchar,"
"type varchar,"
"kind varchar,"
"nation int,"
"carnumber int,"
"elevaltor int,"
"distance int,"
"oil int,"
"temperature int)");
if(success)
{
qDebug()<<QObject::tr("数据库表创建成功!");
}else{
qDebug()<<QObject::tr("数据库表创建失败!");
}
QTime time;
time.start();
query.prepare("insert into mobile values (?,?,?)");
long records=100;
for(int i=0;i<records;i++)
{
query.bindValue(0,i);
query.bindValue(1,"呵呵");
query.bindValue(2,"你好");
query.bindValue(3,"富士康");
query.bindValue(4,rand()%100);
query.bindValue(5,rand()%10000);
query.bindValue(6,rand()%300);
query.bindValue(7,rand()%200000);
query.bindValue(8,rand()%52);
query.bindValue(9,rand()%100);
success=query.exec();
if(!success)
{
QsqlError lastError=query.lastError();
qDebug()<<lastError.driverText()<<QObject::tr("插入失败");
}
}
qDebug()<<QObject::tr("插入 %1 条记录,耗时: %2 ms").arg(records).arg(time.elapsed());
//排序
time.restart();
success=query.exec("select * from mobile order by id desc ");
if(success)
{
qDebug()<<QObject::tr("排序: %1 条记录,耗时: %2 ms").arg(records).arg(time.elapsed());
}else{
qDebug()<<QObject::tr("排序失败!");
}
time.restart();
for(int i=0;i<records;i++)
{
query.clear();
query.prepare(QString("update mobile set attribute=?,type=?,"
"kind=?,nation=?,"
"carnumber=?,elevaltor=?,"
"distance=?,oil=?,"
"temperature=? where id=%1").arg(i));
query.bindValue(0,"四轮");
query.bindValue(1,"轿车");
query.bindValue(2,"富康");
query.bindValue(3,rand()%100);
query.bindValue(4,rand()%10000);
query.bindValue(5,rand()%300);
query.bindValue(6,rand()%200000);
query.bindValue(7,rand()%52);
query.bindValue(8,rand()%100);
success=query.exec();
if(!success)
{
QsqlError lastError=query.lastError();
qDebug()<<lastError.driverText()<<QString(QObject::tr("更新失败"));
}
}
qDebug()<<QObject::tr("更新 %1 条记录,耗时:%2 ms").arg(records).arg(time.elapsed());
time.restart();
query.exec("delete from mobile where id=88");
qDebug()<<QObject::tr("删除一条数据,耗时:%1 ms").arg(time.elapsed());
getchar();
return a.exec();
}
原文链接:https://www.f2er.com/sqlite/201320.html