What is wrong with my SQLite update query - android

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();
}

Related

Update SQLITE query

I need only one table and only one row and update new displacement in it.
For Creating Table
private static void createAllTables(SQLiteDatabase database) {
database.execSQL(" CREATE TABLE IF NOT EXISTS " + IN_RIDE_DATA + " ("
+ TOTAL_DISPLACEMENT_DISTANCE + " TEXT, "
+ USER_ID + " TEXT" + ");");
}
For Updating Table (I remove previous displacement and then insert it new displacement, But i Want to update already existing displacement)
public void insertDisplacement(String id, String displacement) {
try {
deleteDriverLocData();
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} catch (Exception e) {
e.printStackTrace();
}
}
For getting displacement
public String getDisplacement() {
try {
String[] columns = new String[]{NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE};
Cursor cursor = database.query(NewDatabaseForInRideData.IN_RIDE_DATA, columns, null, null, null, null, null);
cursor.moveToFirst();
String totaldisplacement = cursor.getString(cursor.getColumnIndex(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE));
return totaldisplacement;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
For deleting displacement
public void deleteDriverLocData() {
try {
database.delete(NewDatabaseForInRideData.IN_RIDE_DATA, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
You have to make object of contentvalue
ContentValues cv = new ContentValues();
cv.put("displacement1","231"); //These Fields should be your String
values of actual column names
cv.put("displacement2","21");
cv.put("displacement3","21");
after this, you can use update query which SQLite provides
database.update(TableName, cv, "USER_ID ="+id, null);
The following or something along the lines of the following could be used as a replacement for the insertDisplacement method :-
public void insertOrUpdateDisplacement(String id, String displacement) {
ContentValues contentValues = new ContentValues();
contentValues.put(NewDatabaseForInRideData.TOTAL_DISPLACEMENT_DISTANCE, displacement);
String whereclause = NewDatabaseForInRideData.USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = database.query(NewDatabaseForInRideData.IN_RIDE_DATA,
null,
whereclause,
whereargs,
null,null,null
);
if (csr.getCount() < 1) {
deleteDriverLocData();
contentValues.put(NewDatabaseForInRideData.USER_ID, id);
database.insert(NewDatabaseForInRideData.IN_RIDE_DATA, null, contentValues);
} else {
//deleteDriverLocData(); ????? Not sure if required or not.
database.update(NewDatabaseForInRideData.IN_RIDE_DATA,contentValues,whereclause,whereargs);
}
csr.close();
}
This will insert if there is no row (I assume for the user_id) otherwise it will update the displacement column of the existing row.

SQLite - Updating multiple tables

Can anyone help me fixing the problem in my query?
I'm trying to call a function to update multiple tables which have a value of "1" in column "col", but it's not working,
my_function
public long updateNow() {
mDbHelper = new DatabaseHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
int doneClear = 0;
String base_value = "1"; // update all column "col" where value of 1
ContentValues initialValues = new ContentValues();
initialValues.put("col", "0"); // Update all column "col" with 0
doneClear = mDb.update(SQLITE_TABLE_ONE, initialValues, "col=" + base_value, null);
doneClear = mDb.update(SQLITE_TABLE_TWO, initialValues, "col=" + base_value, null);
doneClear = mDb.update(SQLITE_TABLE_THREE, initialValues, "col=" + base_value, null);
doneClear = mDb.update(SQLITE_TABLE_FOUR, initialValues, "col=" + base_value, null);
doneClear = mDb.update(SQLITE_TABLE_FIVE, initialValues, "col=" + base_value, null);
doneClear = mDb.update(SQLITE_TABLE_SIX, initialValues, "col=" + base_value, null);
Log.w(TAG, Integer.toString(doneClear));
return doneClear;
}
This code is not working, i'm can't get why.
Nothing happens in column col.
Anyway, that code is based on my previous query, which is working fine.
working_update_query
public long updates(String recent_value, String _id, String table_name) {
ContentValues initialValues = new ContentValues();
initialValues.put("recent_value", recent_value);
Log.w(TAG, String.valueOf(initialValues) + " WITH ID OF " + _id + " IN TABLE OF " + table_name);
return mDb.update(table_name, initialValues, "_id=" + _id, null);
}
I'm stuck here for almost 1 hour, can't figure out the problem.
Can anyone help me please?
Try this using wildcards to appropriately inject the update parameters, like this:
int updateCount = db.update(
TABLE_NAME,
newValues,
"col = ?",
new String[] {String.valueOf(colValue)}
);
For a quick sample check out this tutorial.

SQLite database update query with multiple where conditions in 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.

Sqlite form of query

i have an issue with both functions
// Insert a new contact in database
public void insertInSignature(String TITLE_SI) {
try {
// Open Android Database
Boolean b = checkIsDataAlreadyInDBorNot("DELIVERY_SLIP",
"TITLE_SI", TITLE_SI);
if(b==false)
{
// cursor is empty
ContentValues initialValues = new ContentValues();
initialValues.put("TITLE_SI", TITLE_SI);
db.insertWithOnConflict("DELIVERY_SLIP", null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
} catch (SQLException sqle) {
Log.e(TAG, "insertUser Error");
Log.e(TAG, "Exception : " + sqle);
} finally {
// Close Android Database
databaseHelper.close();
}
}
public boolean checkIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
db = databaseHelper.getWritableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + "="
+ "`"+ fieldValue+"`";
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
return false;
}
return true;
}
I have this function , I'm inserting signature when it's not on the database.. But the function boolean return an SQLexception i don't know why i found informations about the form , but not for my problem.
Here my log.
http://hpics.li/0ae4ba2
I just want to know if the row exist on my database
here my table.
http://hpics.li/1fd3d9a
Thanks by advance if you need for informations ask me
In SQL, strings are delimited with single quotes ', not backticks `.
To avoid such formatting problems, and SQL injections, you should use parameters instead:
String query = "SELECT * FROM " + TableName + " WHERE " + dbfield + "= ?";
Cursor cursor = db.rawQuery(query, new String[] { fieldValue });
Instead of doing a query every time you want to insert, why not make the TITLE_SI column UNIQUE with ON CONFLICT IGNORE or ONC CONFLICT REPLACE? Then you don't need to check, you simply insert and let the uniqueness constraint manage this for you.

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