Return results from a query

Asked

Viewed 93 times

1

how do I return a value from a "SELECT" method? I have this code:

public void SELECT(String Colunas,String Tabela,String Condicao)
    {
        String QUERY=null;
        if(Colunas!=null && Condicao!=null)
            QUERY=" SELECT "+Colunas+" FROM "+Tabela+" WHERE "+Condicao;
        else if(Colunas!=null&&Condicao==null)
            QUERY=" SELECT "+Colunas+" FROM "+Tabela;
        else if(Condicao!=null&& Tabela==null)
            QUERY=" SELECT "+Colunas+" FROM "+Tabela;
        BD.execSQL(QUERY);
    }

how do I return a set of values in the form of a table?

1 answer

1


In fact, when waiting for a result, the function should be used db.query();

This returns a Cursor, with the result of your consultation:

 // Colunas que seu SELECT vai retornar
    String [] colunas = {"coluna1", "coluna2", "coluna3"};
    // Condicao WHERE do seu SELECT
    String  condicao ="id = ?";
   // Parametros do SELECT (correpondem ao ? da condicao acima)
    String[] parametros = {String.valueOf(id)};

    Cursor cursor = db.query(Tabela, colunas, condicao, parametros, null, null, null, null);

    while(cursor.moveToNext()){
     // Cada tipo de retorno, deve se utilizar o metodo correspondente
    // Pegamos a posicao da coluna1 dentroo do retorno
     int indexColuna1 = cursor.getColumnName("coluna1");
     String s = cursor.getString(indexColuna1);
    int indexColuna2 = cursor.getColumnName("coluna2");
     Long l = cursor.getLong(indexColuna2);
     ....
    }

Follows the documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.