#include <QCoreApplication>
#include<QTextCodec>
#include<QSqlDatabase>
#include<QSqlQuery>
#include<QTime>
#include<QSqlError>
#include<QDebug>
#include<QSqlDriver>
#include<QSqlRecord>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("easybook-33");
db.setDatabaseName("qtDb.db");
db.setUserName("chenqiang");
db.setPassword("123456");
db.open();
//创建数据库表
QSqlQuery query;
bool sucess=query.exec("create table autombil(id int primary key,attribute varchar,type varchar,kind varchar,nation int,carnumber int,elevaltor int,distance int,oil int, temperature int)");
if(sucess)
qDebug()<<QObject::tr("数据库表创建成功");
else
qDebug()<<QObject::tr("数据库表创建失败");
//查询
query.exec("select * from autombil");
QSqlRecord rec=query.record();
qDebug()<<QObject::tr("automobil表字段数")<<rec.count();
//插入记录
QTime t;
t.start();
query.prepare("insert into autombil values(?,?,?,?,?,?,?,?,?,?)");
long records=1000;
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()/100);
query.bindValue(6,rand()/100);
query.bindValue(7,rand()/100);
query.bindValue(8,rand()/100);
query.bindValue(9,rand()/100);
sucess=query.exec();
if(!sucess)
{
QSqlError lasterror=query.lastError();
qDebug()<<lasterror.driverText()<<QString(QObject::tr("插入失败"));
}
}
qDebug()<<QObject::tr("插入%1条记录,耗时:%2ms").arg(records).arg(t.elapsed());
//排序
t.restart();
sucess=query.exec("select * from autombil order by id desc");
if(sucess)
qDebug()<<QObject::tr("排序%1条记录,耗时:%2ms").arg(records).arg(t.elapsed());
else
qDebug()<<QObject::tr("排序失败");
//更新记录
t.restart();
for(int i=0;i<records;i++)
{
query.clear();
query.prepare(QString("update autombil set attribute=?,type=?,"
"Kind=?,nation=?,"
"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()/100);
query.bindValue(5,rand()/100);
query.bindValue(6,rand()/100);
query.bindValue(7,rand()/100);
query.bindValue(8,rand()/100);
sucess=query.exec();
if(!sucess)
{
QSqlError lastError=query.lastError();
qDebug()<<lastError.driverText()<<QString(QObject::tr("更新失败"));
}
}
qDebug()<<QObject::tr("更新%1条记录,耗时:%2ms").arg(records).arg(t.elapsed());
//删除
t.restart();
query.exec("delete from autombil where id=5");
qDebug()<<QObject::tr("删除一条记录,耗时:%1ms").arg(t.elapsed());
return 0;
//输出操作耗时
//return a.exec();
}