QT Creator + SQLite。插入非常慢

时间:2015-03-30 02:36:57

标签: c++ qt sqlite windows-xp 32-bit

我制作了一个在Windows 32bit上运行的终端应用程序。

此应用程序从UDP端口侦听并在SQLite数据库上写入数据

守则:

#include <QUdpSocket>
#include <QTextStream>
#include <QSqlDriver>
#include <QSqlDatabase>
#include <QSqlQuery>


int main()
{
    int i;
    QTextStream qout(stdout);

    //db conn or create db
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("localhost");
    db.setDatabaseName("C:\\db_test\\db.sqlite");

    db.open();
    //create db structure
    QSqlQuery *query = new QSqlQuery(db);
    query->prepare("CREATE TABLE "
                   "MYTABLE("
                   "FIELD_1 VARCHAR(100) NOT NULL, "
                   "FIELD_2 VARCHAR(100) NOT NULL)"
                   );

    if(query->exec() == true){
        qout << "New Database Created" << endl;
    } else {
        qout <<"Database Alredy Exists" << endl;
    }


   //start UDP listener
    QUdpSocket *udpSocket = new QUdpSocket(0);
    udpSocket->bind(7755, QUdpSocket::ShareAddress);
    i=1;

    while (udpSocket->waitForReadyRead(-1)) {

        while(udpSocket->hasPendingDatagrams()) {
            QByteArray datagram;
            datagram.resize(udpSocket->pendingDatagramSize());
            QHostAddress sender;
            quint16 senderPort;

            udpSocket->readDatagram(datagram.data(), datagram.size(),
                                    &sender, &senderPort);

            QString Rec_Data = datagram.data();
            QString Sender_Address = sender.toString();

            QString InsertStr = "INSERT INTO MYTABLE VALUES (:val1, :val2)";
            qout << InsertStr << " " << i << endl;
            query->prepare(InsertStr);
            query->bindValue(":val1", Rec_Data);
            query->bindValue(":val2", Sender_Address);
            if(query->exec() == true){
                qout << "Data stored" << endl;
            } else {
                qout <<"Store Error" << endl;
            }

            i=i+1;
        }
    }
}

我需要每分钟进行大约20,000次查询,但是当我运行(Ctrl + R)时,它每分钟处理大约500次。

我知道有些事情是错的,但我不知道是什么。

1 个答案:

答案 0 :(得分:3)

将多个INSERT操作批处理为单个事务。

单独执行插入操作会将吞吐量限制为每秒约60次插入,因为当SQLite执行写后读取验证时,硬盘驱动器盘片必须完全旋转。

进一步阅读
INSERT is really slow - I can only do few dozen INSERTs per second

相关问题