I am trying to update the database on the basis of incoming parameter but it is not updated.
i am using the following code:
public static void markFavoriteStation(String station, boolean favorite){
Log.d(AppConstants.TAG,"StationListDBIfc: +markFavoriteStation");
String Query = null;
mDb = bartDb.getWritableDatabase();
Query = "update stationlistTable set favorite ='1' where namewithabbr = '+station'";
mDb.rawQuery(Query, null);
Log.d(AppConstants.TAG,"StationListDBIfc: -markFavoriteStation");
}
I think you might have a malformed String definition. You should end the String before concatenating the "station" variable to it, like so:
Query = "update stationlistTable set favorite ='1' where namewithabbr = '" + station + "'";
I can't see any errors. I guess the SQL query has errors or the namewithabbr column doesn't contain what you expect. You should test it in the sqlite3 app.
Related
I am trying to fetch data which contains specific string but query is not working, following is method for fetching data.
public Cursor getSearch(String item) {
SQLiteDatabase db = this.getReadableDatabase();
String mQuery = "SELECT * FROM hadiths WHERE text LIKE %"+item.toString()+"%";
Cursor cursor = db.rawQuery(mQuery, null);
return cursor;
}
Logcat shows following error.
Caused by: android.database.sqlite.SQLiteException: near "%": syntax error (code 1): , while compiling: SELECT * FROM hadiths WHERE text LIKE %fast%
I know that the wildcard %% and string variable item is causing issue but how do I use string variable along with wildcard?
Edit:
As mentioned below by Jiří, parameters should be used to help prevent SQL injection issues.
In order to add parameters you could do something similar to this:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ?”;
String param1 = “%” + item + ”%”;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1});
In order to add another parameter:
String mQuery = "SELECT * FROM hadiths WHERE text LIKE ? AND Name = ?”;
String param1 = “%” + item + ”%”;
String param2 = name;
Cursor cursor = db.rawQuery(mQuery, new String [] {param1, param2});
This code is a bit cumbersome, but it is to illustrate that the parameters must be added in the order in which they are should be added to the query.
see SQLite documentation:
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase
Original answer here for posterity. WARNING Dangerous SQL injection issue!
You need to add single quotes to the query.
String mQuery = "SELECT * FROM hadiths WHERE text LIKE '%"+item+"%'";
Take a look at the SQLite docs:
https://www.tutorialspoint.com/sqlite/sqlite_like_clause.htm
Note: There is no need to use toString() since "item" is already of type String.
My app is using an external SQLite database. The database is created using DB Browser for SQLite software. I am using the following method to query my table with the column ENGLISH (same as en_word). However, problem is the query is slow when my database become large.
public static final String ENGLISH = "en_word";
public static final String TABLE_NAME = "words";
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, mal));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
I tried to create index using DB Browser for SQLite.
CREATE INDEX `kindx` ON `words` ( `en_word` )
However, do I need to modify my code so that my app will query the database using this index? If so, how to do that?
The problem is that SQLite, like most relational databases, can use an index when the parameter to a 'like' clause ends with a wildcard, it cannot use an index when the parameter begins with a wildcard.
So, for this type of query, the index will not be used, and you wind up with a full table scan. This is why it is slower with a large number of rows.
You are actually attempting to do what is known as "full text search", which is not really possible to do efficiently without database features to support it directly.
I have not tried it, but I see that SQLite does have full-text search capabilities, and that it is supported on Android. See Full text search example in Android for an example.
I'm facing an issue with SQLite in Android, I know the solution must be simple, but what I have done is not working !!
// Update a contact with a new name
public void updatename (String phone, String newname) {
newname = newname.replaceAll("'","\'");
String query = "UPDATE contacts SET name = '"+newname+"' WHERE phone = '"+phone+"'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
//db.close();
}
the replace function is not working !!
Use update() to map your strings into placeholders, and Sqlite will escape the strings so that the final command is always valid.
You should always be doing this for every command.
Use PreparedStatement, and should never do the quoting stuff yourself, just unnecessary trouble:
PreparedStatement pstmt = con.prepareStatement("UPDATE constacts SET name = ? WHERE phone = ?");
pstmt.setString(1, "foo")
pstmt.setString(2, '123")
SQL does not use a backslash for escaping.
In SQL string literals, quotes are doubled, so you'd need to replace ' with ''.
But it would be a better idea to use parameters:
String query = "UPDATE contacts SET name = ? WHERE phone = ?";
db.execSQL(query, new Object[]{ newname, phone });
Use Prepared Statements. This sanitizes the input for you before calling the sql command.
How do I use prepared statements in SQlite in Android?
I'm trying to do a SQlite query in Android in which I try to do a parameterized WHERE clause with "?".
Since I want to return all records if a parameter is selected as "Any", I try to implement the follow but don't seems to get the correct result. Can anyone please give me some hints on this?
String select = "SELECT * FROM person_table ";
String where = "WHERE first_name = ? AND gender = ? AND occupation = ?";
String query = select + where;
ArrayList<String> whereArgs = new ArrayList<String>();
if (!first_name.equals("Any"))
whereArgs.add(first_name);
else {
whereArgs.add("NULL");
}
if (!gender.equals("Any"))
whereArgs.add(gender);
else {
whereArgs.add("NULL");
}
if (!occupation.equals("Any"))
whereArgs.add(occupation);
else {
whereArgs.add("NULL");
}
String [] whereArgsStrArray = new String[whereArgs.size()];
whereArgsStrArray = whereArgs.toArray(whereArgsStrArray);
Cursor cursor = db.rawQuery(query,whereArgsStrArray);
As I have read from other post and searched on Google, it seems that if I pass a "null" string to the ? WHERE clause I can return all records from for that particular parameter. I have tried "NULL", "null" or null type in the whereArgs array but still couldn't get it working.
Thanks a lot.
Lawrence
As I have read from other post and searched on Google, it seems that if I pass a "null" string to the ? WHERE clause I can return all records from for that particular parameter.
This is not correct.
To get all records, don't include the criterion such as first_name = ? in your selection in the first place.
I am creating a user login application . I want to show account information of a user when he logs in in textviews of a layout . Here is the image of a layout .
Here is my code for getting data of a user when he logs in :
public Cursor getUserData(String username){
Cursor UserDataCursor = getReadableDatabase().rawQuery(
"SELECT * FROM " + USER_TABLE_NAME + " WHERE " +
USER_NAME + "='" + username+"'", null);
return UserDataCursor;
Here is the code for retrieving data with that class :
String email2 = cursor.getString(cursor.getColumnIndex("email"));
String name2 = cursor.getString(cursor.getColumnIndex("name"));
String pass2 = cursor.getString(cursor.getColumnIndex("pass"));
String gender2 = cursor.getString(cursor.getColumnIndex("gender"));
String date2 = cursor.getString(cursor.getColumnIndex("date"));
String country2 = cursor.getString(cursor.getColumnIndex("country"));
String reg2 = cursor.getString(cursor.getColumnIndex("reg"));
data+=email2+" "+name2+" "+pass2+" "+gender2+" "+date2+" "+country2+" "+reg2+"\n" ;
cursor.moveToNext();
}
It's giving a null pointer exception . What's the problem here ? How can i fix it ?
I think you're making things much harder for yourself by not using the database adapter pattern.
Take a look here for an example of how to set up more abstraction and error handling for your database:
http://www.devx.com/wireless/Article/40842/1954
It is difficult to verify your code, since it is data-dependent. Your column names could be wrong (or one could be missing). Your data type could be wrong. You might be getting a cursor back with NO rows, which you need to check for.
BTW, are you doing cursor.moveToFirst() before starting?
Also, we don't know what's on line 70, where the error occurred, because line numbers are lost in the posting.