Using LIKE and LIMIT in sqlite queries in Android - android

I'm writing a function for an Android app, that should get the first 8 entries (names of cities) of a database which are matching a string.
This is my query:
Cursor cursor = database.rawQuery(
"SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE " + String.format("%s%%", nameLetters) +
" LIMIT " + 8
, null);
This is the resulting error:
android.database.sqlite.SQLiteException: near "LIMIT": syntax error (code 1): , while compiling: SELECT city_name FROM CITIES WHERE city_name LIKE berl% LIMIT 8
I have already checked out other questions on the platform, but could not find any solution helping me out. The database is tested and created correctly and also the search entry is in the database.
Could anybody help?

WARNING: You should NOT use string concatenation with the + operator to insert user input in a SQL query.This leaves your app open to a SQL injection attack. I cannot emphasize this enough. Mitigating this common security flaw should be a top priority for all database developers.
Instead, you should use the ? place holder syntax:
String query = "SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE ?" +
" LIMIT 8";
String[] args = {nameLetters + "%%"};
Cursor cursor = database.rawQuery(query, args);
Even if the database is small and only used for your individual app, it is best to make this syntax a habit. Then when you work on larger, more critical databases, you won't have to worry about this issue as much.
This also has the advantage that it quotes the input for you. You completely avoid the error which you encountered that prompted the original question.

For the sake of completeness I'll turn my comment into an answer, to hopefully help anyone else who may have this issue.
Think you need quotes around the like string eg
SELECT city_name FROM CITIES WHERE city_name LIKE 'berl%' LIMIT 8

Related

How can i order my data Ascending by Time

Like said in the title I am trying to sort my data from sqlite database to ascending time. Here is what I have so far:
Cursor display = db.rawQuery("SELECT * FROM "+TableName + " ORDER BY Time ASC",null );
It displays data however it doesnt sort according to my Time with formade ##.## 24hr time. Hope someone can help.
Try "SELECT * FROM " + tableName + " ORDER BY time(Time)". PS: ASC is default ;)
You can use the strftime() function:
SELECT *
FROM my_table
ORDER BY strftime('%H:%M:%S',my_column)
Here I created a fiddle as example.
The raw query should be something like:
"SELECT * FROM " + TableName + " ORDER BY strftime('%H:%M:%S'," + my_column + ")"
NOTE: strftime() function is the more general function that you can use for manipulate date. But, for this specific case you can also use time(). Indeed, as the document that I linked says:
time(...) is equivalent to strftime('%H:%M:%S', ...)

Closing all cursors associated with sqlite database

Is there a way of closing all cursors that have been used to query a certain database?
I DonĀ“t have the variable names, need a "close.all" sort of code.
Suppose you have some of these cursors, managed by external libraries (Parse Offline DataStore), not by your own code:
Cursor cursorvariablenames = database.rawQuery
("SELECT " + NAME + " FROM " + TABLE_NAME + " WHERE " + DAY_PERIOD[day_counter * 2]
+ " = '" + day + "' AND " + DAY_PERIOD[day_counter * 2 + 1] + " = "
+ Integer.toString(period), null);
I know the name of the sqlite DB = (ParseOfflineStore), and would like to close all cursors that are used by or point toward this DB.
I'll answer my own question to this: There's no solution at sight, no response from Parse team neither.
I am now using SharedPreferences file to handle local data to feed the widget. Any use of Parse Local Datastore will yield into cursor errors over time.
Hope this help someone experiencing the same problem while querying local sqlite databases from homescreen widgets and/or services.
You may try closing your DB withdb.close(); or dbHelper.close();, then all cursors operating on that database should be closed.

How to use INSERT OR REPLACE correctly?

I was originally looking for an INSERT OR UPDATE ability in SQLite but searches showed similar question askers being pointed to using INSERT OR REPLACE.
I'm obviously misunderstanding how this works and obviously I can't use WHERE as I'm getting the following SQLiteException...
08-12 01:38:22.973: ERROR/AndroidRuntime(29242): FATAL EXCEPTION: main
08-12 01:38:22.973: ERROR/AndroidRuntime(29242): android.database.sqlite.SQLiteException:
near "WHERE":
syntax error:
INSERT OR REPLACE INTO SERVERS (
server_name,
service_uri_mobile,
service_uri_wifi,
valid_ssids,
username,password
) VALUES (
'Default',
'http://myserver.com:8790/',
'http://192.168.1.1:8790/',
'[]',
'admin',
'password')
WHERE server_name='Default'
The SQL string I'm using is as follows...
String UpdateString = "INSERT OR REPLACE INTO SERVERS " +
"(server_name,service_uri_mobile,service_uri_wifi,valid_ssids,username,password) VALUES ('" +
locater.getServerName() + "','" +
locater.getServiceUriMobile().toString() + "','" +
locater.getServiceUriWifi().toString() + "','" +
locater.getValidSsids().toString() + "','" +
locater.getUsername() + "','" +
locater.getPassword() + "') " +
"WHERE server_name='" + locater.getServerName() + "'";
I've looked at this page explaining REPLACE but don't quite understand it. How would I re-write the above SQLite command and have it only try to replace the record where the server_name matches (i.e., the equivalent of a WHERE clause)?
Looking at the documentation (and mirroring the comments below the question), REPLACE should be used when UPDATEing (or in other words changing) columns that are UNIQUE. To wit:
REPLACE
When a UNIQUE constraint violation occurs, the REPLACE algorithm
deletes pre-existing rows that are causing the constraint violation
prior to inserting or updating the current row and the command
continues executing normally.
http://sqlite.org/lang_conflict.html

sqlite error in android

I am getting the value from webservice. I am storing in sqlite. While storing in sqlite, I am getting an error. even I replaced single quote with "\'". Which characters are not supported in sqlite?
My error is:
03-26 13:22:22.478: WARN/System.err(311): android.database.sqlite.SQLiteException: near "s": syntax error:
My insert statement is:
myDB.execSQL("INSERT INTO "+TableName
+"("+fieldname+")"
+" VALUES ('"+(homevalue)+"');");
Can anybody tell what to do or give an example?
there is a name which is like "name's" i.e this single quote is problem
Maybe one of your string TableName, fieldname or homevalue contains some quotation. print out the query first and see.
I am just a beginner,
but i think you should write it like this:
"INSERT INTO " + tableName + "(" + feildName + ") VALUES ('" + homeValue + "');"
you put () around the homeValue

Android insert into sqlite database

I know there is probably a simple thing I'm missing, but I've been beating my head against the wall for the past hour or two. I have a database for the Android application I'm currently working on (Android v1.6) and I just want to insert a single record into a database table. My code looks like the following:
//Save information to my table
sql = "INSERT INTO table1 (field1, field2, field3) " +
"VALUES (" + field_one + ", " + field_two + ")";
Log.v("Test Saving", sql);
myDataBase.rawQuery(sql, null);
the myDataBase variable is a SQLiteDatabase object that can select data fine from another table in the schema. The saving appears to work fine (no errors in LogCat) but when I copy the database from the device and open it in sqlite browser the new record isn't there. I also tried manually running the query in sqlite browser and that works fine. The table schema for table1 is _id, field1, field2, field3.
Any help would be greatly appreciated. Thanks!
Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES (" + field_one + ", " + field_two + ")";
although your schema contains three fields. By the way, you can see the log to see the actual error reporting from sqlite.
The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.
I thought it would be useful for others, not to have to dig through the comments to find the right answer.
Since it is a string values you forgot "'" to add...this query will surely work, i tested
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES ('" + field_one + "', '" + field_two + "')";
I changed my code to use myDataBase.insert() instead of rawQuery() and it's working. I'm not sure why the actual sql query didn't work though, so if anyone can shed some light on that I'd still appreciate it.

Categories

Resources