Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Database querys problems!



  • Hi all!

    I'm creating a simple project with SQLITE to store some data, but I'm having some problems!
    When I need the query another table in the middle of another query, the first query only return one item...
    Example: I query the table "produto" ( "product" in english), and then and I need query the "pessoa" ("person" in english) to get the supplier. If I remove the query to get the "pessoa" my "QList<Produto*> " return 3 itens, and if i leave the query to "pessoa" my "QList<Produto*> " only return the first one item on the table.

    @
    QList<Produto*> ProdutoDAO::listarProdutos(QString filtro) {
    QList<Produto*> lista;
    QSqlDatabase database = SingletonSession::getDatabase();
    if (database.open())
    {
    QSqlQuery query(database);
    QString sqlSelect = "SELECT * FROM PRODUTO WHERE";
    sqlSelect.append(" (NOME LIKE '%" + filtro + "%')");
    sqlSelect.append("OR (DESCRICAO LIKE '%" + filtro + "%')");
    query.prepare(sqlSelect);
    query.exec();
    while (query.next()) {
    lista.append( parseRecordToObject(query) );
    }
    query.finish();
    }
    return lista;
    }
    @

    @
    Produto* ProdutoDAO::parseRecordToObject(QSqlQuery query) {
    QSqlRecord record = query.record();
    Produto* obj = new Produto();
    obj->setId(query.value(record.indexOf("id")).toInt());
    obj->setDescricao(query.value(record.indexOf("descricao")).toString());
    obj->setPrecoVenda(query.value(record.indexOf("venda")).toDouble());
    obj->setNome(query.value(record.indexOf("nome")).toString());
    int idFornecedor = query.value(record.indexOf("myFornecedor")).toInt();
    PessoaDAO* pessoaDAO = new PessoaDAO();
    Pessoa* fornecedor = pessoaDAO->buscarPessoa(idFornecedor);
    obj->setMyFornecedor(fornecedor);
    return obj;
    }
    @

    @
    static QSqlDatabase getDatabase()
    {
    QSqlDatabase database = QSqlDatabase::database(getConnectionName());
    if (! database.isValid())
    {
    database = QSqlDatabase::addDatabase(DRIVER, getConnectionName());
    database.setDatabaseName( getDataBaseName() );
    }
    isDataBaseCreated();
    return database;
    }
    @

    I make another project in the past, using the same idea and some resources but using Qt4.8 and I never get problems with that, in this new project I'm getting problems, I'm using Qt5.2.
    Please can some one help me to solve this problem?
    Thanks a lot


  • Lifetime Qt Champion

    Hi,

    Did you check the query that you have generated ? Print the content of lastQuery() so you'll see if there's something fishy with it.

    Hope it helps


Log in to reply