I am using below query to update the column. Now what I want that I want to update these columns only when it is empty or null. How can I achieve this ?
db.execSQL("UPDATE FieldTestDataTemp SET
Image1 = '" + f10.image1 + "',
Image2 = '" + f10.image2 + "',
Image3 = '" + f10.image3 + "',
Image4 = '" + f10.image4 + "',
Image5 = '" + f10.image5 + "',
starRating = '" + starRating1 + "' ");
In mysql we used to use this query
UPDATE table
SET field = 'Your value'
WHERE field
IS NULL
OR LENGTH(field)=0
You have to set multiple query to set multiple column condition.
You can pass parameters like this to a common method that will return you the number of records updated
public int updateRecords(String table, ContentValues values,
String whereClause, String[] whereArgs) {
int a = db.update(table, values, whereClause, whereArgs);
return a;
}
and in this db is SQLiteDatabase object
private SQLiteDatabase db;
According to OP comment
I want to check this for every column in above query.
If I understand you correctly you want to update each column only if this column is empty. For this you need to run separate query for each column.
Sqlite has coalesce function that takes variable number of parameters and returns first not null.
UPDATE field UPDATE FieldTestDataTemp SET Image1 = coalesce(Image1, f10.image1)...
However - this not covers situation with empty fields so you need to carry about them (ex. set to null).
It's also good idea to use prepareStatement() / exec() instead of execSQL(). It allows to use placeholders instead of string concatenation.
You can do a single UPDATE and also check for null/empty:
UPDATE FieldTestDataTemp
SET Image1 = CASE WHEN Image1 IS NULL OR Image1 = ''
THEN f10.image1
ELSE Image1
END,
Image2 = CASE WHEN Image1 IS NULL OR Image2 = ''
THEN f10.image2
ELSE Image2,
...
But this will update every column in the UPDATE statement, even if the base 64 image string already be not null and not empty.
A possibly cleaner way to handle this would be to update each column separately. In this case, we can just add a WHERE clause to only update for empty/null image strings:
UPDATE FieldTestDataTemp
SET Image1 = f10.image1
WHERE COALESCE(Image1, '') <> ''
Related
I am trying to delete a row from my table if 2 columns equal to what the user entered.
E.g. I have 2 textfields in which the user entered something in both e.g. "chicken" and in the other textfield "car". I want to delete the row in which those 2 values are in a row. I think it will be something like: delete from ~tablename~ where food = chicken AND vehicle = car.
Im not sure how to write that in sqlite in android.
I have my SQLitedatabase object and have called the delete method on it, but not sure what to put in the parameters
EDIT = I've managed to do it. Thanks for the below answers but this is how I've done it:
sqlitedb.delete("Random", "food =? AND vehicle=? ", new String[]{tv.getText.toString(),tv1.getText.toString()});
tv and tv1 are textfields in my case. Random is my table's name.
The sql query will look like -
String sqlQuery = "DELETE FROM <table_name> WHERE food = '"+ <food_name> + "' AND vehicle = '" + <vehicle_name> + "'";
You want something like:
String table_name=~tablename~;
String table_column_one=food;
String table_column_two=vehicle;
database.delete(table_name,
table_column_one + " = ? AND " + table_column_two + " = ?",
new String[] {"chicken", "car"});
Check SQLiteDatabase's documentation on delete function for more info.
SQLite accepts conditionals in the WHERE clause as regular SQL.
I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.
I get a string stored in the db to change it. I'm stuck in the method db.update because I have to change all the strings that match the value received. for example I have 15 records in field1 with the string "sun" and change it to "sun1" need to be changed all the correspondents.
I tried that but it does not work
cv.put(MyTable.FIELD1, Ec.getText().toString());
String cat_modificare = (i.getStringExtra("value"));
db.update(MyTable.TABLE_NAME, cv, cat_modificare + "=" + MyTable.FIELD1, null);
When you write something into the whereClause, it is interpreted as a column name unless you format it correctly.
String values should always be used as parameters:
db.update(MyTable.TABLE_NAME, cv,
MyTable.FIELD1 + " = ?",
new String[] { cat_modificare });
Supposing I have this sqlite database structure:
ID PRODUCT_NAME AVAILABILITY
1 foo 0
2 bar 1
3 baz 0
4 faz 1
How cand I modify the value of the AVAILABILITY fom 1 -> 0 where PRODUCT_NAME = 'bar' ?
Something like this,
Pseudocod:
db.execSQL( "UPDATE TABLE" + Table_name + "MODIFY" + availability + "=" + 0 + "WHERE" + product_name + "like ? " + 'bar');
I assume that I also have to drop and recreate table using onCreate() and onUpgrade() methods, right?
Some code will be highly appreciated.
Use this:
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="update "+Table_name+" set availability='0' where product_name like 'bar'";
Object[] bindArgs={"bar"};
try{
db.execSQL(sql, bindArgs);
return true;
}catch(SQLException ex){
Log.d(tag,"update data failure");
return false;
}
You want update not alter. alter is for the database schema, update is for the data stored in it.
For example:
update TABLE_NAME set AVAILABILITY = 0 where PRODUCT_NAME like 'bar';
Also, do not just stick strings together to build an sql query. Use a prepared statement or other statement building library to avoid SQL injection attacks and errors.
You could also use the update(), insert(), query(), delete() methods that Android gives you
// define the new value you want
ContentValues newValues = new ContentValues();
newValues.put("AVAILABILITY", 0);
// you can .put() even more here if you want to update more than 1 row
// define the WHERE clause w/o the WHERE and replace variables by ?
// Note: there are no ' ' around ? - they are added automatically
String whereClause = "PRODUCT_NAME == ?";
// now define what those ? should be
String[] whereArgs = new String[] {
// in order the ? appear
"bar"
};
int amountOfUpdatedColumns = db.update("YourTableName", newValues, whereClause, whereArgs);
The advantage here is that you get correct SQL syntax for free. It also escapes your variables which prevents bad things to happen when you use "hax ' DROP TABLE '" as argument for ?.
The only thing that is still not safe is using column LIKE ? with arguments like "hello%world_" because % (match anything of several chars) and _ (match any 1 char) are not escaped.
You would need to escape those manually (e.g. place a ! before each _ or %) and use
String whereClause = "LIKE ? ESCAPE '!'"
String[] whereArgs = new String[] {
likeEscape("bar")
// likeEscape could be replaceAll("!", "!!").replaceAll("%", "!%").replaceAll("_", "!_") maybe
}
Btw: your single code line should work if you use
db.execSQL( "UPDATE " + Table_name + " SET " + availability + "=0 WHERE " + product_name + " like 'bar'");
SqlLite uses "SQL". You need a SQL "update"
db.execSQL( "update mytable set availability=0 where product_name like '%" + bar + "%'");
Here's a good link for SQL "select", "update", "insert" and "delete" ("CRUD") commands:
http://www.w3schools.com/sql/default.asp
Hi to All I am new to Android.
I am using SQLite DataBase in my Application
meanwhile I am Written Queries using +
Like delete from tablename where value = + value;
this is my query
String delete_query = "delete from " + tableName
+ " where title = '" + title + "'";
database.execSQL(delete_query);
I want to write this Query using placeholder ?.
so that i tried
database.delete(tableName, title + "?" , new String[] {title});
instead "?" i tried (?)/('?')/'?'
but it is giving me an error....
can any one tell me how to write appropriate query using ?.....
Thanks in Advance.
Mahaveer
Make sure you have put the equal sign:-
database.delete(tableName, title + "=?" , new String[] {title});
As far as possible, try to use the less raw queries you can. Two advantages:
Query parameters will be escaped by the system (protection against SQL injection)
The code will be more readable
See the delete function of SQLiteDatabase class
public int delete (String table, String whereClause, String[]
whereArgs)
Convenience method for deleting rows in the
database.
table the table to delete from
whereClause the optional WHERE clause
to apply when deleting. Passing null will delete all rows.
Returns the number of rows affected if a whereClause is passed in, 0
otherwise. To remove all rows and get a count pass "1" as the
whereClause.
In your case:
final String where = "title=?";
final String[] args = new String[] { title };
database.delete(tableName, where, args);