PDA

View Full Version : Query on MS Access DB cause crash



Bruschetta
4th October 2016, 15:33
Hello guys,
i'm trying to make a query on an application that is connected with a .mdb file.
In one of my dialogs i can populate a tableView with no problem and then close the dialog without any problems, let's say i'm reading records from the DB table "PEOPLE".
In the same dialog i have a form to add rows to PEOPLE table. I can add 1-n° rows but when i close the dialog the application crashes EVERY time.
Things like this never happened to me when i was using SQLite DB.

Let me post some of my code, maybe you can help...

This is the way i'm doing my connection with the ACCESS .mdb file

bool connectionOpen(){
static const QString path = PATH;
mydb = QSqlDatabase::addDatabase("QODBC", "Contact");
QString params="Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ="+ path;
mydb.setDatabaseName(params);

if (!mydb.open())
{
qDebug() << "Error: connection with database fail";
qDebug() << mydb.lastError().text();
return false;
}
else
{
qDebug() << "Database: connection ok";
return true;
}
return true;

This is showing the rows and is working as intended


void class::on_pushButton_refreshListP_clicked()
{


QSqlDatabase db = QSqlDatabase::database("Contact");

if (db.isOpen())
{
QSqlTableModel *model = new QSqlTableModel(this,db);
model->setTable("class");
model->setEditStrategy(QSqlTableModel::OnFieldChange);

model->setHeaderData(0, Qt::Horizontal, tr("a"));
model->setHeaderData(1, Qt::Horizontal, tr("b"));
model->setHeaderData(2, Qt::Horizontal, tr("c"));
model->select();

ui->tableView->setModel(model);
}

This is the part of code that is working till i close the dialog... Than the application crashes


if (db.isOpen())
{
QSqlQuery query(db);
// query.setForwardOnly(true);
query.prepare("INSERT INTO class(a, b, c) "
" VALUES ( :a,:b, :c)");


query.bindValue(":a", a);
query.bindValue(":b", b);
query.bindValue(":c", c);


if(query.exec())
{
qDebug() << "exec";
QTimer::singleShot(0, this, SLOT(on_pushButton_refreshListP_clicked()));
}
someone can tell me what im'm doing wrong? I'm missing some configuration for the MS ACCESS?

Thank you for your time and answers

d_stranz
4th October 2016, 16:57
In line 5 of the second piece of code, you are defining a local variable named "db". In line 1 of the third piece of code, you are using another variable named "db". If the one in the third piece of code is a member variable of your class (which can't be named "class" - that's a reserved word in C++ and not legal to use as a class name), then the one in the second piece of code is hiding that one, and therefore the one in the third piece of code is probably never initialized.