Skip to content Skip to sidebar Skip to footer

How To Retrieve A Specific String Data From Sqlite Database By Using 2 String Arguments?

this is my code used which i use for making method String item = item1.getText().toString(); item = item.toLowerCase(); String date = getDate(); edited = new Datahelper(this); ed

Solution 1:

So probably you want to use two arguments in select query so:

You can use two methods:

  • rawQuery()
  • query()

I will give you basic example for both cases.

First:

Stringquery="select * from Table where someColumn = ? and someDateColumn = ?";
Cursorc= db.rawQuery(query, newString[] {textValue, dateValue});

Explanation:

So i recommend to you use ? that is called placeholder. Each placeholder in select statement will be replaced(in same order so first placeholder will be replaced by first value in array etc.) by values from selectionArgs - it's String array declared above.

Second:

rawQuery() method was easier to understand so i started with its. Query() method is more complex and has a little bit more arguments. So

  • columns: represents array of columns will be selected.
  • selection: is in other words where clause so if your selection is KEY_COL + " = ?" it means "where " + KEY_COL + " = ?"
  • selectionArgs: each placeholder will be replaced with value from this array.
  • groupBy: it's multi-row (grouping) function. more about
  • having: this clause is always used with group by clause here is explanation
  • orderBy: is clause used for sorting rows based on one or multiple columns

Also method has more arguments but now you don't need to care about them. If you will, Google will be your friend.

So let's back to explanation and example:

String[] columns = {KEY_COL1, KEY_COL2};
String whereClause = KEY_CATEGORY" = ? and " + KEY_DATE + " = ?";
String[] whereArgs = {"data1", "data2"};

Cursor c = db.query("Table", columns, whereClause, whereArgs, null, null, null);

So whereClause contains two arguments with placeholder for each. So first placeholder will be replaced with "data1" and second with "data2".

When query is performed, query will look like:

SELECT col1, col2 FROMTableWHERE category ='data1'ANDdate='data2'

Note: I recommend to you have look at Android SQLite Database and ContentProvider - Tutorial.

Also i recommend to you an usage of placeholders which provide safer and much more readable and clear solutions.

Solution 2:

You should read any SQL tutorial to find out what a WHERE clause it and how to write it.

In Android, the selection parameter is the expression in the WHERE clause. Your query could be written like this:

c = db.query(DATABASE_TABLE, columns,
             KEY_CATEGORY + " = ? AND " + KEY_DATE + " = ?",
             newString[] { item, date },
             null, null, null);

Post a Comment for "How To Retrieve A Specific String Data From Sqlite Database By Using 2 String Arguments?"