Android: SQL rawQuery with wildcard (%) - java

I'm having a rawQuery() with following sql string similar to this:
selectionArgs = new String[] { searchString };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
but now I have to include a wildcard in my search, so my query looks something like this:
SELECT column FROM table WHERE column LIKE 'searchstring%'
But when the query contains single quotes the following SQLite Exception is thrown: android.database.sqlite.SQLiteException: bind or column index out of range
How can I run a rawQuery with selectionArgs inside a SQL query with wildcard elements?

You have to append the % to the selectionArgs itself:
selectionArgs = new String[] { searchString + "%" };
Cursor c = db.rawQuery("SELECT column FROM table WHERE column=?", selectionArgs);
Note: Accordingly % and _ in the searchString string still work as wildcards!

The Sqlite framework automatically puts single-quotes around the ? character internally.
String [] selectionArgs = {searchString + "%"};
Cursor c;
// Wrap the next line in try-catch
c = db.rawQuery("SELECT column FROM table WHERE like ?", selectionArgs);
That's it.

Brad Hein's and Mannaz's solution did not work for me, but this did:
String query = "SELECT column FROM table WHERE column=%s";
String q = String.format(query, "\""+searchString + "%\"");
Cursor c = db.rawQuery(q, null);

Related

Android SQLite take the first element from database column

I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}

error occur when try to SELECT in sqlite android

so i recently learn to write a code in android using sqlite and i try to select data from sqlite but this error occur
ive tried some suggestion from the internet and read my book but i didnt solve my problem
public Penyakit getPenyakit1(String namaGejal){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\"" + namaGejal + "\"";
Cursor cursor = db.rawQuery(query,null);
Penyakit penyakit = new Penyakit();
if(cursor.moveToFirst()){
cursor.moveToFirst();
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
penyakit.set_namaPen(cursor.getColumnName(1));
penyakit.set_idPenyakit(Integer.parseInt(cursor.getColumnName(2)));
penyakit.set_namGej(cursor.getColumnName(3));
penyakit.set_idGejala(Integer.parseInt(cursor.getColumnName(4)));
cursor.close();
} else {
penyakit=null;
}
return penyakit;
}
this is logcat
Process: com.example.lordbramasta.pakar, PID: 18914
java.lang.NumberFormatException: For input string: "idPen"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.lordbramasta.pakar.DBAdapter.getPenyakit1(DBAdapter.java:79)
i expected the value of idPen get selected , thank you
Your problem is this line:
penyakit.set_nomber(Integer.parseInt(cursor.getColumnName(0)));
cursor.getColumnName(0) returns idPen as this is the name of the only column returned by your query:
SELECT idPen FROM ....
and your code is trying to cast the string "idPen" to an integer.
So getColumnName() returns the name of the column at a specified index and not the value of the column.
You should do
penyakit.set_nomber(Integer.parseInt(cursor.getString(0)));
or if the data type of the column idPen is INTEGER then:
penyakit.set_nomber(cursor.getInt(0));
Also don't try to get any other columns because your query returns only 1.
Note: remove that cursor.moveToFirst(); inside the if block because it is already executed.
Probably you need to use a ' instead of ". So, change the query to the following:
String query = "SELECT idPen FROM " + TABLE_CONTACTS + " WHERE " +
namapen + " =\'" + namaGejal + "\'";
I'm suggesting you to use SQLiteDatabase.query() instead rawQuery like this:
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
"idPen"
};
// Filter results WHERE "namapen" = 'namaGejal'
String selection = "namapen" + " = ?";
String[] selectionArgs = { namaGejal };
// How you want the results sorted in the resulting Cursor
String sortOrder = null; // null for default order
Cursor cursor = db.query(
TABLE_CONTACTS, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
// do something with the cursor
Please take a look Read information from a database
If you want to get all columns data from your TABLE_CONTACTS use SELECT * FROM

Android SQLite get all rows where column contains string always returns -1

textAs the title describes I'm trying to get all rows from a table where strings of a column contains a string anywhere in it. But they way I'm doing it now always return -1 rows.
This is how i'm doing it now but I have no idea of what I might be doing wrong. Suggestions?
Cursor cursor = database.query(DBHelper.TABLE_RECENT, null, DBHelper.COLUMN_TEXT+ " LIKE '%"+club_id+"%'", null, null, null, null);
Just write cursor.moveToFirst(); before getting data from cursor or just under query line.
Hope it will help you.
I guess, you're mis interpreting the structure of query. the second parameter is what you want to select. such as "select column1, column2 etc. Here's a line from my code, and it works for me.
Cursor cursor = db.query(table_employees, new String[] {KEY_ID, KEY_NAME,KEY_DEPARTMENT, KEY_PHONE_NUMBER, KEY_SALARY}, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null);
here "new string[] {key_id.....", the second parameter, is column names, that you wanted to select.
OR
alternately, you may simply do as:
String query = "Select * from "+DB_TABLE+ "Where" +column1 + "=" + t +"and"+ column2 + "=" +tt
db.rawQuery(query);
if you do something like,
String query = "Select * FROM Product where name LIKE '%" + Text + "%'"
Log.d("search query", query);
Cursor c = db.rawQuery(query, null);
c.moveToFirst();

rawQuery selectionArgs not working

I'm trying to query a database with code:
Cursor cursor = db.rawQuery("select * from "+MoneyDBOpenHelper.TABLE_RECORD+" where "+ MoneyDBOpenHelper.ACCOUNT_ID+" = ?",new String []{"1"});
But it's not working at all,I didn't query any data.
While I abandon the usage of selectionArgs with code:
Cursor cursor = db.rawQuery("select * from "+MoneyDBOpenHelper.TABLE_RECORD+" where "+ MoneyDBOpenHelper.ACCOUNT_ID+" = 1",null});
It's working,and I got the data I want.I think those 2 lines of code should compose the same function but they didn't,am I doing something wrong?
1 is a number. "1" is a string.
This is a limitation of the Android dabase API; you should use parameters only for strings.

android cursor order of operations

Is there a way to retrieve the raw query string being generated from a call like the following? I'm trying to figure out how the "?" placeholders get populated.
Cursor cursor = database.query(
adapter.getTable(), // The table to query - String
adapter.getColumns(), // The columns to return - String[]
adapter.getWhereClause(), // The columns for the WHERE clause - String
adapter.getWhereClauseArgs(), // The values for the WHERE clause - String[]
null, // Group by - String
null, // Groups having - String
adapter.getSortBy(), // The sort order - String
adapter.getLimit()); // The limit - String
I'm curious of the order of operations. For example, if the above query translated to the select below with the whereClause args below, would i get result1 or result2? Does it work like the order of operations in math, where statements in parenthesis get executed first? or does it strictly rely on the position of the "?"'s in the string.
String select = "SELECT * FROM table1 WHERE someField = ? AND _id in(SELECT _id FROM table2 WHERE status = ?)";
String[] args = new String[]{ "blue", "active" };
String result1 = "SELECT * FROM table1 WHERE someField = 'blue' AND _id in(SELECT _id FROM table2 WHERE status = 'active')";
String result2 = "SELECT * FROM table1 WHERE someField = 'active' AND _id in(SELECT _id FROM table2 WHERE status = 'blue')";
A quick test will show that it substitutes selection args by the position in the string, without any concept of order of operations.

Categories