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.
Related
I was trying to duplicate this SQLite statement from the line of code below:
Cursor cursor = db.rawQuery("update tbl_details SET ticket = replace(ticket, " + tempID + ", " + ticket + ")", null);
to this one:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("ticket", "replace(ticket, " + tempID + ", " + ticket + ")");
db.update("tbl_details", cv, null, null);
return true;
What I am trying to do is to get a New ID and replace all instances of the old temporary ID in the database. But the code above is changing all the records in ticket column.
Please help. Thank you!
You can use ContentValues to bind literal values only, not expressions like replace(...).
To run the raw UPDATE SQL, just use execSQL() instead of rawQuery(). rawQuery() alone won't actually run the code until the returned Cursor is moved.
Im playing with sql in android and found this issue:
Im reading data from my database:
SQLiteDatabase db = this.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
SingleAppModel singleAppModel = new SingleAppModel();
and when I try to get cursor.getInt(3) over here:
try {
if (cursor.getCount() != 0) {
if (cursor.moveToFirst()) {
singleAppModel.setId(cursor.getInt(0));
singleAppModel.setAppName(cursor.getString(1));
singleAppModel.setPackageName(cursor.getString(2));
singleAppModel.setState(cursor.getInt(3) == 1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
db.close();
It returns error:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
Weird is that if I delete line where Im calling cursor.getInt(3), it works.
Colum with that value exists and Im sure its of type INTEGER.
Also the value of cursor.getColumnCount() is 4 and value of cursor.getCount() is 1 ... so there are definetly some data...
Any advice?
Thankyou.
Rather than using * I suggest you to use,
cursor = db.rawQuery("SELECT COL0, COL1, COL2, COL3 FROM " + TABLE_SINGLE_APPS + " WHERE " + COLUMN_SINGLE_PACKAGE + "=?"
, new String[]{packageName});
Use the appropriate values for COL0, COL1, COL2, COL3 according to your table.
That way you make sure that the order of the columns fetched in the query.
But according to this,
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0`
I need more information to confirm, can you add your table schema, according to the issue there is no 3rd column in the database raw.
Edit:
This can be a small programmer mistake,
Look out for the onCreate and onUpgrade methods in SQLiteOpenHelper implementation
Is there an easy way to update a table in sqlite in android? (like a single line in built method) ? I have a table with few columns and primary is one column. I want to search by the primary key and then update a row in the table.
To use with predefined update method from android, use it as below:
ContentValues args = new ContentValues();
args.put("col_name", "new value");
db.update("table_name", args, String.format("%s = ?", "primary_column"),
new String[]{"primary_id"});
Or to run as a single line, go with this (not recommended):
db.execSQL("UPDATE table_name SET col_name='new_value' WHERE
primary_column='primary_id'");
Read the documentation for SQLiteDatabase.update
You should end up with something like this:
affected = db.update(TABLE_NAME, values, where, whereArgs);
UDPATE
Avoid raw queries using error-prone syntax at all costs. I see a lot of answers here that use a lot of '"' + SOMETHING + "'" ... this is extremely bad practice and you will spend all your time looking for errors on places that are hard to find or simply a complete waste of time.
If you must use raw queries, try forming them with String.format to avoid perilous debug sessions and migraines.
You can use rawQuery like this:
cur = mDb.rawQuery("update " + TABLE_NAME
+ " set column1=mango where id='" + _id + "'",null);
where
cur is Cursor object
TABLE_NAME is NAME OF THE TABLE
_id is name of the column (only example)
Then you should already know what's your primary key.
dbHelper.getWritableDatabase();
ContentValues values = createContentValues(profileVo);
db.update(ProfileVO.TABLE_NAME, values, ProfileVO.COLUMN_ID + "=" + profile.getId(), null)
Here's a good tutorial for you http://www.vogella.com/articles/AndroidSQLite/article.html
The answer is:
http://www.sqlite.org/lang_update.html
and
SQLiteDatabase.rawQuery(...)
Try this:
public void updateFunction(int id) {
String updateStmnt = "UPDATE YOUR_TABLE SET YOUR_COLUMN = "
+ id;
database.execSQL(updateStmnt);
}
Hope it will help.
Using database.update make it simple like this:
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, name);
values.put(MySQLiteHelper.COLUMN_JOB, job);
values.put(MySQLiteHelper.COLUMN_DATE_START, date_start);
database.update(MySQLiteHelper.TABLE_EMPLOYEES, values, MySQLiteHelper.COLUMN_ID+"="+id, null);
I know this a bit old, but in case anyone needed another way:
public boolean updateNote(Note note) {
SQLiteDatabase db = notesDbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NotesDbContract.NoteEntry._ID, note.getId());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_TITLE, note.getTitle());
contentValues.put(NotesDbContract.NoteEntry.COLUMN_NAME_DSECRIPTION, note.getDescription());
int result = db.update(NotesDbContract.NoteEntry.TABLE_NAME,
contentValues,
NotesDbContract.NoteEntry._ID + "=?", new String[]{String.valueOf(note.getId())}
);
db.close();
return result > 0;
}
i have created a database with the table name tbl_customer and tbl_product...i can view the tbl_customer values but can't see tbl_product values.. I use adb shell to confirm my insertion. Can any one plz help me to figure out the issue
private void addProFromDB() {
// TODO Auto-generated method stub
ArrayList<String> results = new ArrayList<String>();
SQLiteDatabase sampleDB = null;
try {
list = (ListView)findViewById(android.R.id.list);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, 1, null);
sampleDB.execSQL("create table tbl_product("
+ "pro_id integer PRIMARY KEY autoincrement,"
+ "pro_name text," + "pro_price integer);");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('1','Milk','60');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('2','Sugar','70');");
sampleDB.execSQL("INSERT INTO " + SAMPLE_TABLE_NAMES
+ " Values ('3','Oil','200');");
Cursor c = sampleDB.query(SAMPLE_TABLE_NAMES, null, null, null, null, null,
null);
char pro_nameColumnIndex = (char) c.getColumnIndexOrThrow("pro_name");
int pro_priceColumnIndex = (int) c.getColumnIndexOrThrow("pro_price");
} finally {
if (sampleDB != null)
sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAMES);
sampleDB.close();
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, new ArrayList()));
new AddStringTask().execute();
}
Also help me how i can get its primary key and display the selected value...
Best regards....
First, it is a good idea to consider using the insert() method on SQLiteDatabase, instead of executing INSERT statements via execSQL(), particularly if you do not have much SQL experience.
Second, normally, an INSERT statement lists the columns to be inserted into, which you are not doing. SQLite might support your syntax, but it makes for more fragile code.
Third, with an autoincrement column, you do not assign your own values, as you are trying to do.
Fourth, you are putting string values into integer columns. SQLite supports that, but not by actually converting the values to integers, but rather storing the strings themselves in the columns, which may not be what you want.
Fifth, getColumnIndexOrThrow() returns an int, not a char.
Sixth, you are deleting your data from the table milliseconds after inserting it, in your finally block, assuming that SAMPLE_TABLE_NAMES is set to tbl_product. If those values are not equal, then you are inserting into and querying from a table that does not exist.
Seventh, your Cursor is dead as soon as you close() the database in your finally block.
Some combination of those probably explains "the issue".
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