Update all rows in a column to new value - android

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

Related

How to bind values to SQLiteStatement for insert query?

Insertion code using SQLiteStatement usually looks like this,
String sql = "INSERT INTO table_name (column_1, column_2, column_3) VALUES (?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);
int intValue = 57;
String stringValue1 = "hello";
String stringValue2 = "world";
// corresponding to each question mark in the query
statement.bindLong(1, intValue);
statement.bindString(2, stringValue1);
statement.bindString(3, stringValue2);
long rowId = statement.executeInsert();
Now this works perfectly fine but the issue I find here is that I have to be very careful about binding correct data to corresponding indexes. A simple swap of index will give me an error.
Also let's say in future my column_2 gets dropped from the table, then I would have to change all the indexes after the column_2 index otherwise the statement won't work. This seems trivial if I just have 3 columns. Imagine if a table has 10-12 (or even more) columns and column 2 gets dropped. I'll have to update the index of all the subsequent columns. This whole process seems inefficient and error prone.
Is there an elegant way to handle all this?
Edit : Why would I want to use SQLiteStatement ? Check this :Improve INSERT-per-second performance of SQLite?
Insertions can be done with ContentValues:
ContentValues cv = new ContentValues();
cv.put("column_1", 57);
cv.put("column_2", "hello");
cv.put("column_3", "world");
long rowId = db.insertOrThrow("table_name", null, cv);
But in the general case, the most correct way would be to use named parameters. However, these are not supported by the Android database API.
If you really want to use SQLiteStatement, write your own helper function that constructs it from a list of columns and takes care of matching it with the actual data. You also could write your own bindXxx() wrapper that maps previously-saved column names to parameter indexes.
You can use ContentValues with beginTransaction into SQLite that is quite easy as well as faster then prepared statements
For this you have to create ContentValues Array previously or create Content values object into your loop. and pass into insert method .this solution solve your both of problem in one.
mDatabase.beginTransaction();
try {
for (ContentValues cv : values) {
long rowID = mDatabase.insert(table, " ", cv);
if (rowID <= 0) {
throw new SQLException("Failed to insert row into ");
}
}
mDatabase.setTransactionSuccessful();
count = values.length;
} finally {
mDatabase.endTransaction();
}

Insert data into SQLite table in the same row

I am trying to insert data in an SQLite database from different places in different columns at a time. When I view the database, each insert takes one row. My databases lookes like this:
How do I achieve this? Any suggestions?
In order to insert a new row within your database, you need to add the following code into the Java class that manages your SQLite database:
public long insertRow(String name, String email)
{
ContentValues contentValues = new ContentValues();
contentValues.put(rowName, name);
contentValues.put(rowEmail, email);
return database.insert(databaseTable, null, contentValues);
}
The variable database refers to the database you attempting to insert the row. The variable databaseTable refers to the table you want to insert the row into. If you are attempting to update an existing column, you need to add the following code into the Java class that manages your database:
public boolean updateRow(long id, String name, String email)
{
ContentValues contentValues = new ContentValues();
contentValues.put(rowName, name);
contentValues.put(rowEmail, email);
return database.update(databaseTable, contentValues, rowId + “=” + id, null) > 0;
}
In order to call this function, you need to pass the id of the row and the desired values to pass in order to update them.

Avoid duplicate entries in SQLite

I am writing a small application in android to store basic details about person using SQLite.
I insert data using this function
public void insertData(String user,String p_no,SQLiteDatabase db)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
The above function allows duplicate names to be stored.
So I wrote a function that will first check whether a name exits and then enter.
public void insertData(String user,String p_no,SQLiteDatabase db)
{
Cursor resultSet=db.rawQuery("select NAME from MYTABLE where NAME = '"+user+"'",null);
if(resultSet==null)
{
ContentValues cv = new ContentValues();
cv.put(NAME, user);
cv.put(PHONE, p_no);
db.insert("MYTABLE", null, cv);
}
else Toast.makeText(context,user+" already exists",Toast.LENGTH_SHORT).show();
}
But the problem is now toast comes up every time I insert meaning even if the row is unique it is not inserted.
Why resultSet is not null even when there is no such row?
It is because RawQuery never returns null cursor, and that's what your checking criteria is, so it is failing always, and trying to add new value in DB.
I am not able to find the documentation where I learned it, but I will update as soon as possible.
You can check if you have values in cursor using -
if(cursor.moveToFirst())
because it is possible to have an empty cursor. Change your check like
if(cursor.getCount() == 0)
this way, if the cursor is not null, you check if it contains something too.
Probably this is not the best way to handle duplicates, in my opinion. You should mark your column as unique, and use insertWithConflict, to decide what to do in case you have already an entry with that value
Check
if (resultset.getCount() == 0)
Also, create Name as unique key to avoid duplicates. Instead of checking it everytime.

How to update only last record of SQLite database in android?

I am using SQLite database in android. I need to update the record based on some condition. But there are multiple records that fulfills the condition, so all records are getting updated. I need to update only last one. Please help me.
Thanks in advance
Here is my code
public void UPDATE_INVOICE(int invoice_id,int owner_id,int vehicle_id,String invoice_date,String invoice_time,String dest,String distance,String validity_date, int qty,String local_var)
{
SQLiteDatabase db=getWritableDatabase();
ContentValues values = new ContentValues();
values.put(INVOICE_NUMBER, invoice_id);
values.put(INVOICE_DATE, invoice_date);
values.put(INVOICE_TIME, invoice_time);
values.put(INVOICE_VALIDITY_DATE, validity_date);
values.put(INVOICE_QTY, qty);
values.put(INVOICE_LOCAL, local_var);
db.update(TABLE_INVOICE_DETAILS, values, INVOICE_OWNER_ID_REF+"="+owner_id+" and "+INVOICE_VEHICLE_ID_REF+"="+vehicle_id, new String[]{});
}
If someone else will find that question, then possible answer is:
update table1 set last_accessed_dt = datetime('now') where _id = (SELECT MAX(_id) FROM table1);

Easiest way to enter more than one rows in a table

When the first time i am running the app, i want to create a table and enter some rows into the table. For doing this, i wrote this bit of code and it is working fine:
//Creating the table
db.execSQL(MRM_BOOKING_LOGIN_TABLE_CREATE);
//Setting the values in the table
ContentValues contentValuesLogin = new ContentValues();
contentValuesLogin.put(USER_ID, "asdf");
contentValuesLogin.put(PASSWORD, "1234");
//Inserting a row in the table
db.insert(MRM_BOOKING_LOGIN_TABLE, null, contentValuesLogin);
But i want to enter at least 15 to 20 rows in the table. Is it a good idea that every time after inserting one row, i will clear the ContentValues object (or create another object of ContentValues) and enter another row in the newly created table? In this way, the lines of code will increase a lot as well. I am sure there might be some other better alternative way to do the same. Please suggest
Regards,
I think, the only way to insert multiple records via db.insert is to use a loop. Combine it together with SQLite Transaction and it will speed up the process.
A sample code:
try {
// open the database
db.beginTransaction();
for (your objects) {
ContentValues cv = new ContentValues();
cv.put(COL1, obj.p1);
cv.put(COL2, obj.p2);
//.....
long id = db.insertOrThrow(DATABASE_TABLE, COL_Id, cv);
}
db.setTransactionSuccessful();
} catch (Exception e) {
throw e;
} finally {
db.endTransaction();
// close database
}
You can insert multiple rows using ContentResolver.bulkInsert (Uri url, ContentValues[] values).
More information can be had from here:
Insertion of thousands of contact entries using applyBatch is slow
Hope this will help you.

Categories

Resources