Return results of a query

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?

    
asked by anonymous 10.04.2016 / 17:46

1 answer

1

Actually, when you expect a result, you should use the function db.query();

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

 // 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);
     ....
    }

Follow the documentation.

    
11.04.2016 / 17:14