PDA

View Full Version : Qt SQLite



metRo_
23rd October 2010, 11:48
Hi, i'm doing a little aplication in qt that insert data in a SQLite, in my pc it's ok but in other pc's the aplication don't insert the data :s

The aplication: http://dl.dropbox.com/u/6416035/release.zip

The code:


#include "mainwindow.h"
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlTableModel>
#include <QTableView>
#include <QString>
#include <QDir>
#include <QFileDialog>
#include <QMessageBox>
#include <QSqlRecord>
#include <QLabel>
#include <QProgressBar>
#include <QLayout>
#include <QVBoxLayout>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{

QString dir = QFileDialog::getOpenFileName(this, tr("Open Directory"),"");//,tr("SQLite (*.*)"));
//qDebug()<<dir;
QString path(dir);
//path.append(QDir::separator()).append("dbpass");
path = QDir::toNativeSeparators(path);
//qDebug()<<path;
//db.setDatabaseName(path);

db = QSqlDatabase::addDatabase("QSQLITE");
//db.setDatabaseName("thomsonkeysDB");
db.setDatabaseName(path);

if (db.open()) {
// Try to locate the contacts database.
// If it is not available create it.
if (db.tables().indexOf("thomsonkeys") == -1) {
QSqlQuery query(db);
query.prepare("CREATE TABLE thomsonkeys (ssid VARCHAR(6), pass VARCHAR(10))");
if (!query.exec())
qCritical() << query.lastError();
}
} else {
qCritical() << db.lastError();
}

QVBoxLayout *layout = new QVBoxLayout;
progresso = new QProgressBar;
progresso->setMaximum(174680046);
layout->addWidget(progresso);

QWidget *w=new QWidget();
w->setLayout(layout);
this->setCentralWidget(w);


QTimer::singleShot(100, this, SLOT(teste()));
}

MainWindow::~MainWindow()
{

}

void MainWindow::teste(){
QString dir = QFileDialog::getOpenFileName(this, tr("Open Directory"),"",tr("Texto (*.txt)"));
QFile f(dir);
f.open(QIODevice::ReadOnly);
if(f.isOpen())
{
QSqlQuery query(db);

int step=174680046/100;
int bytesProcessed=0;
QString linha;
QStringList list;
progresso->setValue(bytesProcessed);
while (not f.atEnd()){
linha = f.readLine().data();
bytesProcessed+= linha.size();
list = linha.split(":");
query.exec("insert into thomsonkeys values('"+list.at(0)+"', '"+list.at(1)+"')");
if (bytesProcessed%step<=10){
qDebug()<<"bytesProcessed:"<<bytesProcessed;
progresso->setValue(bytesProcessed);
}
}
progresso->setValue(bytesProcessed);

}
else
{
QMessageBox::warning(this,"Erro","Sem ficheiro com as passwords!");
}
}

Lykurg
23rd October 2010, 15:38
What is the error you get from your query? Also you should consider using prepare() to avoid a potential security leak because of SQL injection.

metRo_
23rd October 2010, 15:39
I discover that the problem is that the sqlite file wasn't created :S

HabeebALLAH
12th December 2010, 10:35
Thankyou. I used your database creation/open technique to create the SQLite file on the harddisk and it is working very fine.