jeudi 30 avril 2015

next() in QSqlQuery returns the last record in the table

When search button is clicked, it shows the first record in the table like this;

void EditEntry::on_search_button_clicked() {
    searchText = search->text();
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");
    bool ok = db.open();
    if (ok) {

        QSqlQuery query1("SELECT * FROM table_name WHERE last_name LIKE '%Nana%'");
        if (query1.first()) {
            //show first record in the table where last name like Nana
        }
}

I am trying to make the query move to the next record in the table by the click of a button like this;

void EditEntry::on_next_button_clicked() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");
    bool ok = db.open();
    if (ok) {
        QSqlQuery query1("SELECT * FROM table_name WHERE last_name LIKE '%Nana%'");
        if (query1.isActive()) {
            while (query1.next()) {
                //show the next record in the table with last name like Nana
            }
} 

And showing the previous record with the name like 'Nana' like this;

void EditEntry::on_previous_button_clicked() {
    searchText = search->text();
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("database.db");
    bool ok = db.open();
    if (ok) {
        QSqlQuery query1("SELECT * FROM table_name WHERE last_name LIKE '%Nana%'");
        if (query1.isActive()) {
            while (query1.previous()) {
                //show previous record in the table where last name like Nana
            }
}

The on_search_button_clicked() works well by showing the 1st record with last name like 'Nana'. The on_next_button_clicked() shows the last record in the table with name like 'Nana' instead of the next record after the 1st (the table has 3 records with last name like 'Nana'). The on_previous_button_clicked() button doesn't work at all, it shows nothing even though i expect it to show the previous record with last name like 'Nana'. How do i get these buttons to work as i expect?

Aucun commentaire:

Enregistrer un commentaire