SQLite database update query with multiple where conditions in Android - android

I want to update my database table with multiple where conditions. I already did with single where condition
db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
new String[] { String.valueOf(items.getAuthor()) });
Now i want 2 where condition.
P.S :- No raw query

You can separate the different WHERE conditions with ANDlike this:
db.update(TABLE_NAME,
contentValues,
NAME + " = ? AND " + LASTNAME + " = ?",
new String[]{"Manas", "Bajaj"});

The way I solved my need
public boolean checkHususiKayit(String baslik, String tarih) {
boolean varMi = false;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_BASLIK,
DBHelper.COLUMN_H_TARIH,
DBHelper.COLUMN_H_YOK_TUR,
DBHelper.COLUMN_H_AD,
DBHelper.COLUMN_H_WEB_ID,
DBHelper.COLUMN_H_NUMARA,
DBHelper.COLUMN_H_YURD_ID,
DBHelper.COLUMN_H_YETKILI_AD,
DBHelper.COLUMN_H_YETKILI_ID,
DBHelper.COLUMN_H_TEL,
DBHelper.COLUMN_H_EMAIL,
DBHelper.COLUMN_H_ADDRESS,
DBHelper.COLUMN_H_VAR,
DBHelper.COLUMN_H_GOREVLI,
DBHelper.COLUMN_H_YOK,
DBHelper.COLUMN_H_IZINLI,
DBHelper.COLUMN_H_HATIMDE};
String whereClause = DBHelper.COLUMN_H_BASLIK + " = ? AND " + DBHelper.COLUMN_H_TARIH + " = ?"; // HERE ARE OUR CONDITONS STARTS
String[] whereArgs = {baslik, tarih};
Cursor cursor = database.query(DBHelper.TABLE_NAME_HUSUSI, kolonlar, whereClause, whereArgs, null, null, null + " ASC");
while (cursor.moveToNext()) {
varMi = true;
}
database.close();
cursor.close();
return varMi;
}

THIS CAN ALSO BE DONE LIKE THIS
public void UpdateData(int Cid,int flag,String username,String password)
{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Status",flag);//I am updating flag here
database.update(TABLE_NAME, cv, ""+KEY_UserName+"= '"+ username+"' AND "+KEY_CID+"='"+Cid+"' AND "+KEY_Password+"='"+password+"'" , null);
database.close();
}

Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});
where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.

Related

What is wrong with my SQLite update query

My SQLite update query doesn't work, but returns no error...
public void updateData(String stickerPackTitle, String installed) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_INSTALLED, installed);
db.update(TABLE_NAME, cv, "' " + COL_PACK_NAME + " = " + stickerPackTitle + " '", null);
}
Replace update line with this:
db.update(TABLE_NAME, cv, COL_PACK_NAME + " = '" + stickerPackTitle + "'", null);
Below is the right method to use update query in SQLite. You should keep where clause and your where arguments in different parameters. And yes, don't forgot to close the database connection.
db.update(TABLE_NAME, cv, COL_PACK_NAME + " =?", new String[] stickerPackTitle});
db.close();
Try this type of code :
public void update_PrimaryOffer(PrimaryOffer p)
{
// TODO Auto-generated method stub
ContentValues contentValues = new ContentValues();
contentValues.put("businessId", p.getBusinessId());
contentValues.put("primaryOfferDiscount", p.getPrimaryOfferDiscount());
contentValues.put("offerImage", p.getOfferName());
contentValues.put("businessType", p.getBusinessType());
contentValues.put("businessName", p.getBusinessName());
contentValues.put("businessInformation", p.getBusinessInformation());
contentValues.put("businessImage", p.getBusinessImage());
contentValues.put("offerName", p.getOfferName());
contentValues.put("offerAddress", p.getOfferAddress());
contentValues.put("phoneNumber", p.getPhoneNumber());
contentValues.put("originalPrice", p.getOriginalPrice());
contentValues.put("expiryDate", p.getExpiryDate());
contentValues.put("latitude", p.getLatitude());
contentValues.put("longitude", p.getLongitude());
contentValues.put("likeStatus", p.getLikeStatus());
contentValues.put("favoriteStatus", p.getFavoriteStatus());
contentValues.put("likeCount", p.getLikeCount());
// contentValues.put("DateTime", p.getDateTime());
Cursor cursor = sqLiteDatabase.rawQuery("select * from "+TABLE_RECENT_PRIMARY_OFFER+";", null);
if (cursor.moveToFirst()) {
do {
int ii = sqLiteDatabase.update(TABLE_RECENT_PRIMARY_OFFER, contentValues, "businessId="+ p.getBusinessId(),null);
System.out.println("SQLITE UPDATE SCHEDULER---->" + ii);
}while(cursor.moveToNext());
}
cursor.close();
}

Selecting NULL values in Android SQLite

I'm executing the following method with no success beacause of the selectArgs being incorrect (at least this is what I believe.
findAll:
public Collection<Object> findAllByCodigoSetorOrderByStatusWhereDataAgendamentoIsNull(Integer vendedor) {
Collection<Object> objects = null;
String selection = Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " OR " + Object.FIELDS[20] + "=?" + " AND " + Object.FIELDS[6] + "=?";
String[] selectionArgs = new String[] { "''", "'null'", "NULL", String.valueOf(vendedor) };
Collection<ContentValues> results = findAllObjects(Object.TABLE_NAME, selection, selectionArgs, Object.FIELDS, null, null, Object.FIELDS[4]);
objects = new ArrayList<Object>();
for (ContentValues result : results) {
objects.add(new Object(result));
}
return objects;
}
findAllObjects:
protected Collection<ContentValues> findAllObjects(String table, String selection, String[] selectionArgs, String[] columns, String groupBy, String having, String orderBy) {
Cursor cursor = null;
ContentValues contentValue = null;
Collection<ContentValues> contentValues = null;
try {
db = openRead(this.helper);
if (db != null) {
cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
contentValues = new ArrayList<ContentValues>();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
contentValue = new ContentValues();
for (int c = 0; c < cursor.getColumnCount(); c++) {
contentValue.put(cursor.getColumnName(c), cursor.getString(c));
}
contentValues.add(contentValue);
cursor.moveToNext();
}
}
return contentValues;
} finally {
close(db);
}
}
How can I correctly select and compare a column to - null, 'null' and '' using the db.query?
Android's database API does not allow to pass NULL values as parameters; it allows only strings.
(This is a horrible design bug. Even worse, SQLiteStatement does allow all types for parameters, but works only for queries that return a single value.)
You have no choice but to change the query string to blah IS NULL.
Old question but i was still stuck on this for a few hours until i found this answer. For whatever reason this strange behaviour (or bug) still exists within the android sdk, if you want to query against null values simply do
SQLiteDatabase db = getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("columnName", newValue);
String nullSelection = "columnName" + " IS NULL";
db.update("tableName", contentValues, nullSelection, null);
db.close();
In this example i am updating values, but it is a similar concept when just selecting values
As mentioned in other answers, for null "IS NULL" need to be used. Here is some convenience code for having both null and strings (I'm using delete in the example but the same can be done for other methods, e.g. query):
public void deleteSomething(String param1, String param2, String param3) {
ArrayList<String> queryParams = new ArrayList<>();
mDb.delete(TABLE_NAME,
COLUMN_A + getNullSafeComparison(param1, queryParams) + "AND " +
COLUMN_B + getNullSafeComparison(param2, queryParams) + "AND " +
COLUMN_C + getNullSafeComparison(param3, queryParams),
queryParams.toArray(new String[0]));
}
private String getNullSafeComparison(String param, List<String> queryParams) {
if (param == null) {
return " IS NULL ";
} else {
queryParams.add(param);
return " = ? ";
}
}
You can bind NULL values to SQLiteStatement:
SQLiteDatabase db = getWritableDatabase();
SQLiteStatement stmt = db.compileStatement("UPDATE table SET " +
"parameter=? WHERE id=?");
if (param == null)
stmt.bindNull(1);
else
stmt.bindString(1, param);
stmt.execute();
stmt.close();
db.close();

Android SQLite Query: Trouble with WHERE clause

Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}

Cursor returning null

public String getContact(String searchName) {
SQLiteDatabase db = this.getReadableDatabase();
String[] args = { searchName };
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES
+ " WHERE name =? ", args);
String iName = null, iDiretor = null, iGenre = null;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
iName = cursor.getString(cursor.getColumnIndex(KEY_NAME));
iDiretor = cursor.getString(cursor.getColumnIndex(KEY_DIRECTOR));
iGenre = cursor.getString(cursor.getColumnIndex(KEY_GENRE));
cursor.moveToNext();
}
cursor.close();
The iName variable is working fine but the other two are returning null. Any help?
Use the SQLiteDatabase query methods instead of rawQuery for the best results.
db.query(TABLE_MOVIES, null, "name = ?", args, null);
This is preferred because rawQuery is easy to mess up and doesn't protect against SQL injections.
Try this way:
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES + " WHERE name LIKE ? ", args);
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_MOVIES
+ " WHERE name LIKE "+searchName, null); // Put Like When your are comparing String

Change a value in a column in sqlite

I need to update a value in a column from a certain table. I tried this :
public void updateOneColumn(String TABLE_NAME, String Column, String rowId, String ColumnName, String newValue){
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = "+newValue+" WHERE "+Column+ " = "+rowId;
db.beginTransaction();
SQLiteStatement stmt = db.compileStatement(sql);
try{
stmt.execute();
db.setTransactionSuccessful();
}finally{
db.endTransaction();
}
}
and I call this method like this :
db.updateOneColumn("roadmap", "id_roadmap",id,"sys_roadmap_status_mobile_id", "1");
which means that I want to set the value 1 in the column sys_roadmap_status_mobile_id when id_roadmap = id.
The problem is that nothing happens. Where is my mistake?
Easy solution:
String sql = "UPDATE "+TABLE_NAME +" SET " + ColumnName+ " = '"+newValue+"' WHERE "+Column+ " = "+rowId;
Better solution:
ContentValues cv = new ContentValues();
cv.put(ColumnName, newValue);
db.update(TABLE_NAME, cv, Column + "= ?", new String[] {rowId});
The below solution works for me for updating single row values:
public long fileHasBeenDownloaded(String fileName)
{
SQLiteDatabase db = this.getWritableDatabase();
long id = 0;
try {
ContentValues cv = new ContentValues();
cv.put(IFD_ISDOWNLOADED, 1);
// The columns for the WHERE clause
String selection = (IFD_FILENAME + " = ?");
// The values for the WHERE clause
String[] selectionArgs = {String.valueOf(InhalerFileDownload.fileName)};
id = db.update(TABLE_INHALER_FILE_DOWNLOAD, cv, selection, selectionArgs);
}
catch (Exception e) {
e.printStackTrace();
}
return id;
}

Categories

Resources