Artificial truth

The more you see, the less you believe.

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

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 ("");
if(! ()){

//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( (QIODevice::ReadOnly)){
    QSqlQuery que;
    QTextStream ts (&f);

    //Travel through the csv file "excel.csv"
        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.chop(1); // remove the trailing comma
        req.append(");"); // close the "VALUES([...]" with a ");"
    f.close ();