Query error in SQLite [duplicate] - android

This question already has answers here:
Update table using rawQuery() method does not work
(5 answers)
Closed 6 years ago.
I've tried this code to update all my values in column sync to 0...
How can I solve this issue?
public boolean updatesync()
{
SQLiteDatabase db=this.getWritableDatabase();
db.rawQuery("update patients set sync = '0'",null);
return true;
}
This code is not working. I need to change the entire column value of sync to 0. How can I do that? I've found this code as working when searching, but it's not working for me. How can I solve that?
Please help.

Use execSQL() instead of rawQuery().
rawQuery() just compiles the SQL but does not execute it until the returned Cursor is moved. execSQL() both compiles and executes the SQL.

for update value in Sqlite , try this one
public int updateName(string name,String Id){
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + Id, null) > 0;
}
*** Note ***
KEY_NAME= Column name (value will update),
DATABASE_TABLE =Table name ,
KEY_ROWID = Column name (value will update depends on this column name)

Related

Delete specific record in sqlite table based on two criteria: _id and column

I have created a sqlite table for my android app, this table has 5 columns and multiple rows, the columns being: _id, column1, column2, column3, column4.
I want to delete a specific record, for instance the record stored in column3 corresponding to _id (in a different class are the getters and setters, for this I've named the class "TableHandler")
I guess that I'm a bit confused, following is what I was planning, but for column3 I'm not sure what should be the argument, I just want to delete whatever is in that column position corresponding to _id
public void deleteValueColumn3(TableHandler value){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ? AND " + KEY_COLUMN3 + " = ?",
new String[] {String.valueOf(value.getID()), ?????????);
db.close();
}
The ???????? is that I'm stuck there, maybe the whole method needs to be rewritten, I would appreciate your input.
Thanks
If you want to delete the whole record, just use the _id of the record in delete method, because that is the primary key for your table and therefore is unique. If you'd rather keep the record, you con always use the SQLiteDatabase.update method, specifying null as the new value that will replace column3 value; check out that column3 declaration has no NOT NULL tag, otherwise that could easily throw exception at you.
SQLite does not allow you to delete columns for a specific row.
You can only delete ROWS of data (delete the row that has the column _ID = 1).
Here's a quick tutorial on SQL.
How about updating that column with a null value, rather than using delete()?
ContentValues cv = new ContentValues();
cv.putNull(KEY_COLUMN3);
db.getWritableDatabase().update(
TABLE_NAME,
cv,
KEY_ID + "=?",
new String[]{String.valueOf(keyIdValue)});

How to get the id of the lastest object i have just added to the database? [duplicate]

This question already has answers here:
Get last inserted value from sqlite database Android
(10 answers)
Closed 8 years ago.
I have created a database that holds names, info and also gives an "_id" for each object that gets save to the database.
now i want with the next function to get at the end the id that the new added object is getting - i have tried the next code - but im sure it's not the right way
public long insertAuto(Student student){
SQLiteDatabase db = dbOpen.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(Constants.STUDENT_NAME, student.getName());
vals.put(Constants.STUDENT_INFO, movie.getInfo());
db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);
//this is where i thinks is my mistake!
long id = student.getId();
db.close();
return id;
}
so thank you for any kind of help
Check the documentation of SQLiteDatabase.insert()
It returns the newly inserted rowId for you.
public long insertAuto(Student student){
SQLiteDatabase db = dbOpen.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(Constants.STUDENT_NAME, student.getName());
vals.put(Constants.STUDENT_INFO, movie.getInfo());
long id = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);
db.close();
return id;
}
Use the return value of SQLiteDatabase.insert() method.
As the documentation states, this method returns
the row ID of the newly inserted row, or -1 if an error occurred
You can try this :
String query = "SELECT ROWID from TABLE_NAME_STUDENTS order by ROWID DESC limit 1";
Cursor c = db.rawQuery(query);
if (c != null ) {
c.moveToFirst();
id = c.getLong(0);
}
1/ If you generate id in the application yourself, then what you're doing is correct.
lastId = theLastSavedStudentObject.get(id);
2/ Look at your code, it seems you let the database generates the id automatically (MySQL autoincrement perhaps), then the last id must be select from database or by return from the insert function.
lastSaveId = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);
OR query directly from DB using this SQL query:
select max(id) from mytable; (for autoincrement ID)
Whenever you run a query for insertion on database, it returns the row id of the currently inserted row as long value.
long id = db.insert(Constants.TABLE_NAME_STUDENTS, null, vals);
return id;
This row id will be unique and can be used in further queries.

Update all rows in a column to new value

Apologies, I am sure this has been asked plenty of times but I have searched around for a good example and haven't been able to find one.
I'd like to run a method to insert a value into a particular column for all rows in a table. To give you an idea of the methods and queries I'm working with, this is my working update method for my Students table:
public void updateStudent(long id,String name, String age, String points,
String teachernote,byte[] blob) {
ContentValues cv = new ContentValues();
cv.put(Students.STUDENT_NAME, name);
cv.put(Students.STUDENT_AGE, age);
cv.put(Students.STUDENT_POINTS, points);
cv.put(Students.TEACHERNOTE, teachernote);
cv.put(Students.IMAGE,blob);
db = sqlHp.getWritableDatabase();
db.update(Students.TABLE, cv, Students.STUDENT_ID+"="+ id, null);
db.close();
}
I'm after a query to update STUDENT_POINTS for all rows. Any help would be much appreciated, thank you.
If you want to update all rows you have to remove the where clause. In your example you should remove Students.STUDENT_ID+"="+ id, from db.update(Students.TABLE, cv, Students.STUDENT_ID+"="+ id, null);

Sqlite UPDATE with parameterised IN (...) clause [duplicate]

This question already has answers here:
IN clause and placeholders
(9 answers)
Closed 10 years ago.
In my app I'm working with sqlite database - and I hit a strange issue.
I have a table that looks like this:
_id field1 field2 status
--- ------ ------ ------
1 value value ...
2 value value ...
...
At one place, I need to update some rows to set them to another status, so I'm trying
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("status", STATUS_SENT);
Set<Integer> ids = datasource.getCompletedIds();
String idparam = TextUtils.join(",", ids);
int cnt = db.update(TABLE_ORDERS, cv, "_id in (?)", new String[] { idparam });
Log.d("db", "updated " + cnt + " rows");
db.close();
However nothing gets updated - and db.update returns 0. What am I missing?
I'm not happy recommending not using parameters, but it this case, it's actually easier than formatting all those ? markers (and with plain integers, just as safe):
db.update(TABLE_ORDERS, cv, "_id IN (" + idparam + ")", null);
Unfortunately you must list one insertion character ? for each id in your Set...
A popular fix is to write a quick utility to add the appropriate number of ?s based on the Set's size.

SQLite query and update error in Android

I'm new in Android. I'm trying to update the table in my first Application using SQLite. But when ı looked to the table from SQLite Manager ı saw that the table didn't updated. I couldn't find where the problem is?
public void EntryHesapla(int yilsql, String aysql,int digerTaksitlersql,
int digersql,int maasSelosql,int maasHilalsql,int digerGelirlersql,
int toplamHarcamasql,int toplamGelirsql,int eldeKalansql) {
ContentValues cv = new ContentValues();
cv.put(C_YIL, yilsql);
cv.put(C_AY, aysql);
cv.put(C_DIGERTAKSITLER, digerTaksitlersql);
cv.put(C_DIGER, digersql);
cv.put(C_MAASSELO, maasSelosql);
cv.put(C_MAASHILAL, maasHilalsql);
cv.put(C_DIGERGELIRLER, digerGelirlersql);
cv.put(C_TOPLAMHARCAMA, toplamHarcamasql);
cv.put(C_TOPLAMGELIR, toplamGelirsql);
cv.put(C_ELDEKALAN, eldeKalansql);
String[] selectionArgs=new String[]{yilsql+"", aysql};
String entryHesaplaSQL="SELECT c_id FROM harcamalar WHERE "+C_YIL+"= ? AND "+C_AY+"= ?";
Cursor cursor=ourDatabase.rawQuery(entryHesaplaSQL, selectionArgs);
cursor.moveToFirst();
cursor.moveToPosition(cursor.getCount() - 1);
int index=cursor.getInt(cursor.getColumnIndex(C_ID));
if(index>=0)
ourDatabase.update(DB_TABLE, cv, C_ID+"="+index, null);
else ourDatabase.insert(DB_TABLE, null, cv);
}
cursor.getColumnIndex(C_ID);
returns the column index for the C_ID column in your query. It is 0, as there is only 1 column in your query.
If you want the value for this column, you need to call getInt(index) (see getColumnIndex for further details.)

Categories

Resources