Artificial truth

The more you see, the less you believe.

[archives] [latest] | [homepage] | [atom/rss]

import cvs to sqlite with qt.
Sun 13 May 2012 — download

I was quite surprised when I discovered that Qt doesn't provide a native way to import csv directly into a single sql table. Here is a simple way to do this:

//Open the database
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName ("test.dev.db");
if(!db.open ()){
    exit(-1);
}

//Suppression + creation of the table
que.exec("DROP TABLE main;");
que.exec ("CREATE TABLE main(
id int,
    lieu char(255),
    latitude int,
    longitude int,
    nom char(255) );");

//Open the "excel.csv" file
QFile f("excel.csv");
if(f.open (QIODevice::ReadOnly)){
    QSqlQuery que;
    QTextStream ts (&f);

    //Travel through the csv file "excel.csv"
    while(!ts.atEnd()){
        QString req = "INSERT INTO main VALUES(";
        // split every lines on comma
        QStringList line = ts.readLine().split(',');
        /*for every values on a line,
            append it to the INSERT request*/
        for(int i=0; i<line .length ();++i){
            req.append(line.at(i));
            req.append(",");
        }
        req.chop(1); // remove the trailing comma
        req.append(");"); // close the "VALUES([...]" with a ");"
        que.exec(req);
    }
    f.close ();
}