#include <QtCore/QCoreApplication>
#include <QTextCodec>
#include <QtSql/QtSql>
#include <QDebug>
#include <QString>
#include <QTime>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("123.db");
//db.setDatabaseName(":memory:");
if(!db.open()){
qDebug()<<QObject::tr("无法打开数据库");
return false;
}
QSqlQuery query;
bool bSuccess = query.exec("CREATE TABLE automobil (id INT PRIMARY KEY,attribute VARCHAR,type VARCHAR,kind VARCHAR,nation INT,carnumber INT,elevaltor INT,distance INT,oil INT,temperature INT)");
if(bSuccess){
qDebug()<<QObject::tr("数据库表创建成功\n");
}else{
qDebug()<<QObject::tr("数据库表创建失败\n");
}
QTime t;
t.start();
query.prepare("INSERT INTO automobil 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()%10000);
query.bindValue(6,rand()%300);
query.bindValue(7,rand()%20000);
query.bindValue(8,rand()%152);
query.bindValue(9,rand()%100);
bool bSuccess = query.exec();
if(!bSuccess){
QSqlError lastError = query.lastError();
qDebug()<<lastError.driverText();
qDebug()<<QObject::tr("插入失败");
}
}
qDebug()<<QObject::tr("插入%1 条记录,耗时:%2ms").arg(records).arg(t.elapsed());
t.restart();
bSuccess = query.exec("SELECT * FROM automobil ORDER BY id DESC");
if(bSuccess){
qDebug()<<QObject::tr("排序%1条记录,耗时:%2 ms").arg(records).arg(t.elapsed());
}else{
QSqlError lastError = query.lastError();
qDebug()<<lastError.driverText();
qDebug()<<QObject::tr("排序失败");
}
t.restart();
for(int i = 0;i<records;i++){
query.clear();
query.prepare(QString("UPDATE automobil 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()%20000);
query.bindValue(7,rand()%52);
query.bindValue(8,rand()%100);
bSuccess = query.exec();
if(!bSuccess){
QSqlError lastError = query.lastError();
qDebug()<<lastError.driverText()<<QString(QObject::tr("更新失败"));
}
}
qDebug()<<QObject::tr("更新%1条记录,耗时:%2 ms").arg(records).arg(t.elapsed());
t.restart();
bSuccess = query.exec("DELETE FROM automobil WHERE id=200");
if(!bSuccess){
qDebug()<<QObject::tr("删除失败");
}else{
qDebug()<<QObject::tr("删除一条记录,耗时:%1 ms").arg(t.elapsed());
}
return a.exec();
}
红色部分时 报错 : 插入失败 Unable to fetch row
绿色部分时 正常