Multiple Where clause in Android SQL statement - android

I am having some problem with the SQL statement for Android. Basically I have two where clause, bookID and userID and the SQL statement that I am having now:
public boolean updateLoan(String bookID, String userID, String currentDate) {
try {
ContentValues cv = new ContentValues();
cv.put("loanDate", currentDate);
mDb.update("loanBook", cv,
" bookID= '" + bookID + "'", null);
return true;
} catch (Exception ex) {
Log.e(TAG, ex.toString());
return false;
}
}
So I wonder how could I put two where clause in this method as currently I only can where clause by bookID. Do I simply put an "&" and continue the SQL statement?
Thanks in advance.

Do I simply put an "&" and continue the SQL statement?
Yes, use AND instead of &

Related

Android - SQLiteException while deleting record

Currently We have one application in which we are receiving many crash reports while deleting record from database .
Here is method in which app is crashing.
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = '" + nickName + "'", null);
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
but we am getting following exception:
android.database.sqlite.SQLiteException: near "adz": syntax error
(code 1): , while compiling: DELETE FROM groups_map WHERE
gmap_nick_name = ''adz.'
Any help will be appreciated.
Look at delete signature:
int delete (String table, String whereClause, String[] whereArgs)
Third argument is where args:
You may include ?s in the where clause, which will be replaced by the
values from whereArgs. The values will be bound as Strings.
It's automatically escaped, so there is no need to put quotes (', ") manually.
Use where args instead of strings concating:
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + " = ?", new String[] { nickName });
Try Like This
public int deleteGroupMap(String nickName) {
SQLiteDatabase database = this.getWritableDatabase();
try {
database .execSQL("DELETE FROM "+ TABLE_NAME_GROUP_MAP + " WHERE " + COLUMN_GMAP_NICK_NAME + " = "+nickName+"");
database .close();
} catch (Exception e) {
e.printStackTrace();
} finally {
database.close();
}
return 0;
}
Try this
return database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "= ?" , new String[]{Long.toString(nickName)});
You should also use parameter markers because appending values directly is error prone when the source contains special characters.
try following because it will also prevent SQL injections to your app
database.delete(TABLE_NAME_GROUP_MAP, COLUMN_GMAP_NICK_NAME + "=?", new String[]{String.valueOf(nickName));

Android sqlite update not done in table

Following is my code for update record done.
try {
String str_edit = edit_note.getText().toString();
Toast.makeText(getApplicationContext(), str_edit,
Toast.LENGTH_LONG).show();
Toast.LENGTH_LONG).show();
String rawQuery="UPDATE " + GlobalVariable.getstr_tbl_name()
+ " SET note = '" + str_edit + "' where name = '"
+ str + "' ";
db.execSQL(rawQuery);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Code for Display:
try {
Cursor note_cursor = db.query(GlobalVariable.getstr_tbl_name(),
new String[] { "note" + " as note" }, "name" + "=?",
new String[] { GlobalVariable.getstr_food_name() }, null,
null, null);
if (note_cursor.moveToFirst()) {
int notecol = note_cursor.getColumnIndex("note");
do {
String str = note_cursor.getString(notecol);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_LONG).show();
edit_note.setText(str);
} while (note_cursor.moveToNext());
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I am getting all variable value i.e global variables and all but update does not reflects on table.
What wrong i am done?
whenever we try to update our database then just clean and uninstall your app then again install may be some changes not take place when we don't uninstall it if u find correct then tell other wise we will see the next
Should
int notecol = note_cursor.getColumnIndex("name");
instead be
int notecol = note_cursor.getColumnIndex("note");
since in the first block of code you are updating note..
The problem is that you try to update your DB using a rawQuery method instead of a execSql. RawQuery is intended to retrieve data from your database, while execSql lets you
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
You can also consider to use public int update (String table, ContentValues values, String whereClause, String[] whereArgs) method.

Sqlite Insert or Update

I wanted to update my existing table with new values but some of them are fresh. I have written code for updating the table, but how can I do both operations(update & insert) simultaneously.
Just use replace() method in SQLiteDatabase. Its simply insert a new row if no row with same key is not exists in database. Otherwise it replaces the existing row.. Its simple than other ways.. For more info refer the documentation..
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Try something like this:
String username="xyzName";
Cursor cur_user = my_db.rawQuery("SELECT _id from user_info where user_name ='"
+ username + "'", null);
if (cur_user.getCount() > 0) {
// User exists. Update information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
String whereClause = "user_name = '" + username + "'";
try {
my_db.update("user_info", cvUserInfo, whereClause, null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Insert the information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
cvUserInfo.put("user_name", username);
my_db.insert("user_info", null, cvUserInfo);
}
You will need to have one column except id, on which you can check. I had user name as a unique column to check for existing record.
Hope this helps.

Update doesn't work sqlite android

Having problem updating a column in a table. I tried both of these solutions:
this.openDataBase();
String SQLStatement = "update " + TABLE_POSES;
SQLStatement += " set " + COLUMN_SKIP + "=" + SKIP + " Where ";
SQLStatement += COLUMN_ID + "=" + String.valueOf(skipPoseId);
myDataBase.rawQuery(SQLStatement, null);
this.close();
and this:
this.openDataBase();
ContentValues args = new ContentValues();
args.put(COLUMN_SKIP,SKIP);
myDataBase.update(TABLE_POSES, args, COLUMN_ID + "=" + String.valueOf(skipPoseId),null);
this.close();
Neither of these code snippets work and I am not getting any exceptions thrown. What am I doing wrong?
You should use the second method using update() and you should check the return value. If the value is zero, then the state of the database isn't what you expect and no rows were updated. If the row is not zero then the updating is succeeding.
If anything is wrong with your accessing the database an exception will be thrown before the update() call.
I would take advantage of the args parameter of update() like so:
myDataBase.update(TABLE_POSES, args, COLUMN_ID + " = ?", new String[]{ Long.toString(skipPoseId) });
Use update like this,
String query="UPDATE tablename SET columnname="+var+ "where columnid="+var2;
sqlitedb.execSQL(query);
Just write your update query in String query and execute.
if you use db.begintransaction() in your code you must call db.setTransactionSuccessful() before db.endtransaction() such as:
try {
SQLHelper dbHelper = new SQLHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();
...................
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
catch (Exception ex){
}
I had the exactly same issue. After much thought and debugging I saw that the WHERE condition wasn't addressing any rows of the table.
The odd thing is that the myDatabase.update command giving 1 as the return and I was understanding it as 1 row affected by the update.

Android SQLite Update not working

I am trying to update one column for any number of rows.
Here is the function:
public void setAwardsSyncComplete(String[] ids) {
String inArray = StringUtils.separateCommas(ids);
db.beginTransaction();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(COL_SYNCED, true);
int rowsAffected = db.update(TABLE, contentValues, COL_ID + " IN (" + inArray + ")", null);
} catch (Exception e) {
DebugLog.e("Error in transaction", e.toString());
} finally {
db.endTransaction();
}
}
What is strange is that the rowsAffected returns correctly (i.e. rowsAffected > 0), but the column values remain null.
Am I overlooking something very simple here?
Thanks.
As you're using transactions, you need to call db.setTransactionSuccessful(); at the end of the try clause. Without this, the update gets rolled back.
See SQLiteDatabase.beginTransaction
Hope this helps,
Phil Lello
You need to call db.setTransactionSuccussful() after db.update otherwise any changes will be rolled back when you call endTransaction().
there's no explicit boolean type in sqlite tables?
what data type is the COL_SYNED column you are trying to update?
and you will need to call db.setTransactionSuccussful()
I think there is a problem on your update..
You need to loop your array and update each one by one..
private int _rowsAffected;
foreach (var a in inArray)
{
_rowsAffected= db.update(TABLE, contentValues, COL_ID + " = (" + a +")", null);
}
db.Commit();
db.setTransactionSuccussful();
if(_rowsAffected > 0)
//Success
Regards

Categories

Resources