0

I'm trying to access mysql a database in qt c++.

I have different tables and want to output them on a QTableView.

I use the QSqlTableModel, which works great, but as soon as I want to filter the results I run into problems..

Here is the main part of my source code:

mModelContacts->setTable("contacts");
mModelContacts->select();
mUi->tableContacts->setModel(mModelContacts);

void MainWindow::on_submitContactsButton_clicked()
{

switch(mUi->comboBoxContacts->currentIndex())
{
    case 0:
        mModelContacts->setFilter("contacts_id = "+mUi->searchContactsLine->text());
        break;
    case 1:
        mModelContacts->setFilter("contacts_firstName LIKE "+'%'+mUi->searchContactsLine->text()+'%');
        break;
    case 2:
        mModelContacts->setFilter("contacts_lastName LIKE "+'%'+mUi->searchContactsLine->text()+'%');
        break;
    case 3:
        mModelContacts->setFilter("contacts_city LIKE "+'%'+mUi->searchContactsLine->text()+'%');
        break;
    case 4:
        mModelContacts->setFilter("contacts_phoneNumber LIKE "+'%'+mUi->searchContactsLine->text()+'%');
        break;
}

mModelContacts->select();
mUi->tableContacts->setModel(mModelContacts);

}

The ID Filter (case 0) works fine. But everything else (firstname, lastname etc.) does not. I just get an empty table showed. So I can see the column names (therefore I think that my sql syntax is correct) but there is no entry, no matter what I type in.

Is there a mistake in my source code? Or how can I get this to work?

Mike
  • 8,055
  • 1
  • 30
  • 44
linux_lover
  • 125
  • 1
  • 13

1 Answers1

1

There is a problem with you adding the char* C-style string ("contacts_firstName LIKE ") to the the char ('%'), this will lead to the following:

  1. the char('%') will be casted to an integer (its representation in ASCII), in order to perform the addition, have a look at this.
  2. the integer resulted from the cast (37) will be added to the char* C-style string, this will get you into memory that you haven't initialized (maybe other C-style strings that you have in your read-only data section).
  3. after that QString adds data from the evil pointer resulting above (until it finds a '\0' character) to the string that is in your line edit, resulting in a QString that you are clearly not aiming for. . .

in summary you should replace your setFilter calls with something like this:

mModelContacts->setFilter(QString("contacts_firstName LIKE '%")+mUi->searchContactsLine->text()+QString("%'"));
Mike
  • 8,055
  • 1
  • 30
  • 44