How to view generated SQL Statements for Android/SQLite - android

I wonder if there is an easy way to see the SQL generated by the SQLiteQueryBuilder class in Android? I want to use this for debugging purposes.
I looked around and searched but couldn't find anything. Either it's not easy or it's super obvious.

What it basically does is calling the SQLiteQueryBuilder#buildQueryString static method, so you can try to call that method passing the correct parameters. This is how the method looks like:
public static String buildQueryString(
boolean distinct, String tables, String[] columns, String where,
String groupBy, String having, String orderBy, String limit) {
if (TextUtils.isEmpty(groupBy) && !TextUtils.isEmpty(having)) {
throw new IllegalArgumentException(
"HAVING clauses are only permitted when using a groupBy clause");
}
if (!TextUtils.isEmpty(limit) && !sLimitPattern.matcher(limit).matches()) {
throw new IllegalArgumentException("invalid LIMIT clauses:" + limit);
}
StringBuilder query = new StringBuilder(120);
query.append("SELECT ");
if (distinct) {
query.append("DISTINCT ");
}
if (columns != null && columns.length != 0) {
appendColumns(query, columns);
} else {
query.append("* ");
}
query.append("FROM ");
query.append(tables);
appendClause(query, " WHERE ", where);
appendClause(query, " GROUP BY ", groupBy);
appendClause(query, " HAVING ", having);
appendClause(query, " ORDER BY ", orderBy);
appendClause(query, " LIMIT ", limit);
return query.toString();
}

Related

Using brackets and ? in Android SQLiteDatabase query()

I'm trying to execute a query on a SQLiteDatabase in Android, using the query() function. I want to pass the argument in SelectionArgs[], but when I'm using a IN statement, it doesn't seem to substitute the '?' with the correct argument.
My query looks like this:
temp = database.query(TABLE_NAME_ENTRIES,
new String[] {"_id", "Entry", "Summary"},
"_id IN ( ? )",
new String[] {ids}, null, null, null);
and it results in an empty Cursor. Debug gives me the information that the executed query uses a statement "_id IN ( ? )", showing that it doesn't seem to replace the '?' as expected. When I change the query to
temp = database.query(TABLE_NAME_ENTRIES,
new String[] {"_id", "Entry", "Summary"},
"_id IN ( " + ids + " )",
null, null, null, null);
instead, I get the expected result.
I'm really stupid on this problem, any ideas what I'm doing wrong?
You could use a workaround like this - creating a method that generates dynamically your string with ? and , and put it in the query like this:
String[] ids = { "id1", "id2" }; // do whatever is needed first
String query = "SELECT * FROM table"
+ " WHERE _id IN (" + makePlaceholders(ids.length) + ")";
Cursor cursor = mDb.rawQuery(query, ids);
String makePlaceholders(int len) {
if (len < 1) {
// It will lead to an invalid query anyway ..
throw new RuntimeException("No placeholders");
} else {
StringBuilder sb = new StringBuilder(len * 2 - 1);
sb.append("?");
for (int i = 1; i < len; i++) {
sb.append(",?");
}
return sb.toString();
}
}
P.S. I think that the spaces before and after the question mark in your query could be wrong there, but I didn't test it, so I can't be 100% sure

Query a Sqlite Database Using an Array Android

I have researched a handful of other forums with a similar topic and I have yet to find an answer to this frustrating issue. I am trying to use an array to check if a column in my database has one of the multiple values in the array. My cursor is as follows:
public Cursor notificationQuery(String geoIds) {
Log.e("STRINGS", geoIds);
return mDb.query(Constants.TABLE_POI_NAME,
new String[]{Constants.TABLE_COLUMN_ID, Constants.TABLE_COLUMN_POI_NAME,
Constants.TABLE_COLUMN_LATITUDE, Constants.TABLE_COLUMN_LONGITUDE,
Constants.TABLE_COLUMN_GEO_ID},
Constants.TABLE_COLUMN_GEO_ID + " IN (?)",
new String[]{geoIds},
null, null, null, null);
}
geoIds is currently an array of two values which has been converted into a string. The logged value of that string is below:
21007b0f-6b20-4eff-9a76-b412db8daa2e,26c695d6-6cb4-4c74-9933-281813a06fd9
Those are to separate Id values separated by a comma. When I test each one individually using "= ?" instead of "IN (?)" I get a proper match with the database and my cursor returns a value. However, when combined my cursor returns nothing when it should return two rows from the database. Please help me solve this issue! Thanks!
Consider a function String makePlaceholders(int len) which returns len question-marks separated with commas, then:
public Cursor notificationQuery(String geoId1,String geoId2) {
//assume we split this geoIds to 2 different values. you need to have 2 strings no 1
String[] ids = { geoId1, geoId2 }; // do whatever is needed first depends on your inputs
String query = "SELECT * FROM "+ Constants.TABLE_POI_NAME + " WHERE "+
Constants.TABLE_COLUMN_GEO_ID +" IN (" + makePlaceholders(names.length) + ")";
return mDb.rawQuery(query, ids); // ids is the table above
}
Here is one implementation of makePlaceholders(int len):
String makePlaceholders(int len) {
if (len < 1) {
// It will lead to an invalid query anyway ..
throw new RuntimeException("No placeholders");
} else {
StringBuilder sb = new StringBuilder(len * 2 - 1);
sb.append("?");
for (int i = 1; i < len; i++) {
sb.append(",?");
}
return sb.toString();
}
}
Or more simply, use the geoIds variable directly:
public Cursor notificationQuery(String geoIds) {
Log.e("STRINGS", geoIds);
return mDb.query(Constants.TABLE_POI_NAME,
new String[]{Constants.TABLE_COLUMN_ID, Constants.TABLE_COLUMN_POI_NAME,
Constants.TABLE_COLUMN_LATITUDE, Constants.TABLE_COLUMN_LONGITUDE,
Constants.TABLE_COLUMN_GEO_ID},
Constants.TABLE_COLUMN_GEO_ID + " IN (" + geoIds + ")",
null, null, null, null, null);
}
This approach is less secure but will likely give you the result you expect.

Looking for record in Android SQlite Database by String

public boolean findContact(String phoneNumber) {
boolean exists = false;
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + SQLITE_TABLE + " WHERE " + KEY_PHONENUMBER + " = " + phoneNumber, null);
if (mCursor.moveToFirst()) {
exists = true;
} else exists = false;
return exists;
}
It is supose to return true when a row with telephone number exists (format is +441212312312 - String ). The problem is that it always return false, even if such a row exists. I think that a problem is with WHERE clause, but LIKE don't work either. How can I do this ?
thanks for your response
i suggest you that use query, insert, update or delete clauses directly from SQLiteDatabase object instance ;)
And see link below to know which values you will have returned
SQLiteDatabase Object
And i suggest too that if you just want if it exists don't ask about * ... ask about _id because it's primary key it has a index ;)) <-- it means faster
Here i seek a specific row:
public Cursor getEnvio(final String empresa_p, final String albaran_p) {
return db.query(Envio.KEY_ENVIO, new String[] { Envio.KEY_ID,
Envio.KEY_ALBARAN, Envio.KEY_LINEA, Envio.KEY_TIPO,
Envio.KEY_DESTINATARIO, Envio.KEY_DIR, Envio.KEY_POBLACION,
Envio.KEY_POBLACION, Envio.KEY_PRIORIDAD, Envio.KEY_INCIDENCIA,
Envio.KEY_EMP, Envio.KEY_CPOSTAL }, Envio.KEY_EMP + " = ? AND "
+ Envio.KEY_ALBARAN + " = ? ", new String[] { empresa_p,
albaran_p }, null, null, Envio.KEY_LINEA);
}

SQLite select query with where cluase

I have the following function for SQLite select statement
public Boolean itemFound(String cartId,Long ItemId){
SQLiteDatabase db = this.getReadableDatabase();
Log.d("search",cartId+"--"+ItemId);
try {
String where = COL_ITEM_CART_ID+"='"+cartId+"' and "+COL_ITEM_ID+" ="+ ItemId+"";
Log.d("where===============", where);
String columns[] = new String[] { COL_ITEM_ID,COL_ITEM_NAME, COL_ITEM_PRICE, COL_ITEM_ADDDATE,COL_ITEM_QUANTITY,COL_ITEM_CART_ID }; // > null means * (all)
Cursor c = db.query(TABLE_NAME,
columns ,
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?" ,
new String[]{cartId,String.valueOf(ItemId)},
null,
null,
COL_ITEM_ADDDATE+" desc");
int numRows = c.getCount();
c.close();
db.close();
if(numRows>0)
return true;
else
return false;
} catch (SQLException e) {
db.close();
return false;
}
}
where the parameters are :
Long type itemId= 9882889921
String type cartId = ca1745ef-24eb-4da8-a1ea-9650d78ba5c0
Despite there is recode with these data. the returned rows is 0 , why ?
You have wrapped a ? in single quotes, change this:
COL_ITEM_CART_ID+"='?' and "+ COL_ITEM_ID + "=?"
The line above is trying to literally match COL_ITEM_CART_ID to a question mark, change it like this:
COL_ITEM_CART_ID + "=? and "+ COL_ITEM_ID + "=?"
The query method will sanitize your data input for you, so when you wrap the ?s with apostrophes, the apostrophes become part of the input string itself. This is causing your query to return 0 rows.
To fix the problem, remove change all instances of '?' to ?.

SQLite select issue

I have written method which should return string with data from select query, but it doesn't work perfectly as I would like, here is method:
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
return cursor2.toString();
}
it returns some kind of string but, it is not the thing I want [ the string it returns is something like "SQLite.database.#" etc
You're returning the internal name of the Cursor you got from the query, not any data from the query results.
You should use something like:
cursor2.moveToFirst(); // position the cursor at the first returned row
String col = cursor2.getString(the_index_of_the_column_you_want);
cursor2.close();
return col;
Make sure you test for errors though (there might be no rows returned at all), and read the Cursor API docs.
Rewrite your code as
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
//Write these codes
if(cursor2.moveToFirst()) {
cursor2.close(); //You should close your cursor
return cursor2.getString(0); //index of your kolumna field
} else {
cursor2.close(); //You should close your cursor
return null; //Return some error msg, to notify that data not found
}
}
You can use the code below. You may catch exception after the try block. Even if you don't, you're guaranteed that the close() on the cursor will be called! I also suggest to always use English names for your vars.
public String selectorDanych(String kolumna, String log){
String test = "Select "+ kolumna + " from "+ Usr_TABLE+ " where "+colLogin + " ='" +log+"';";
Cursor cursor2 = sqLiteDatabase.rawQuery(test, null);
if (cursor2 != null && cursor2.moveToFirst()) {
try { //use try - finally to close the cursor in the finally block
int index_kolumna = cursor2.getColumnIndexOrThrow(kolumna);
String kolumna_val = cursor2.getString(index_kolumna);
} finally {
if (cursor2 != null && !cursor2.isClosed()) {
cursor2.close();
}
}
}

Categories

Resources