Home > Mobile >  How can I convert this query into a rawQuery in Android Studio?
How can I convert this query into a rawQuery in Android Studio?

Time:03-22

This is the query that I need to convert to a rawQuery in Android Studio:

select EVENT from U7toU16Events where EVENT_CODE like 'U14%' into a rawQuery (Similar like operator examples: https://www.w3schools.com/sql/sql_like.asp)

The number '14' is a string variable called 'communityGamesAge' that can be any number from 5 to 16.

I tried this but my syntax is wrong:

c = db.rawQuery("select EVENT from U7toU16Events where EVENT_CODE like 'U" communityGamesAge "%'", new String[]{});

This is my code

''' //method to query db and return a result

public String getEvents(String communityGamesAge){

    c = db.rawQuery("select EVENT from U7toU16Events where EVENT_CODE like 'U" communityGamesAge "%'", new String[]{});

    //c = db.rawQuery("select EVENT from U7toU16Events where EVENT_CODE like 'U14%'", new String[]{});

    StringBuilder buffer = new StringBuilder();
    while (c.moveToNext()){
        String event = c.getString(1);
        buffer.append(" * ").append(event).append("\n");
    }
    return buffer.toString();
}

'''

Any help would be much appreciated.

CodePudding user response:

Concatenating the parameters is never a good idea and it is not recommended mostly for safety reasons.

Use a ? placeholder for the parameter in the sql statement and pass the parameter communityGamesAge in the array of the 2nd argument of rawQuery():

c = db.rawQuery("select EVENT from U7toU16Events where EVENT_CODE like 'U' || ? || '%'", new String[] {communityGamesAge});
  • Related