How to write SQL statement containing 2 conditions in android - android

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.

Related

How to update column only is its empty in sqlite?

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, '') <> ''

Delete the last row in a table SQLite android

I am developing an android app where I want to delete the last row in one of my database table. I have tried the code below, but its throwing a syntax error.
public void deletelatestprofilefromsystemsettings()
{
String maxid = System_id + "="+"SELECT MAX ("+System_id+") FROM" +TABLE_SYSTEM_SETTINGS;
getWritableDatabase().delete(TABLE_SYSTEM_SETTINGS, maxid ,null);
}
Please help! Thanks!
You are lacking a space after the FROM, and subqueries must be written in parentheses:
String maxid = System_id + "=" +
"(SELECT MAX("+System_id+") FROM " + TABLE_SYSTEM_SETTINGS + ")";
You are trying to execute a DELETE with a SELECT in the same query. AFAIK you shouldn't do it. You have to execute the SELECT query first, in order to retrieve the desired id, then execute the deletion. In other words, execute Cursor c = getWritableDatabase().query(), read the id from the cursor, then use it in getWritableDatabase().delete().
Also, add a space after ") FROM", so it becomes ") FROM " in order to avoid a syntax error.

Query doesnt work on android, column '_id' does not exist?

I hope anyone can help me with this.
I'm using sqlite3 on my android app. I'm trying to do this query:
mCursor = conexion.getDatabase().rawQuery("SELECT employee.name, company.name FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
This is my schema:
CREATE table company ("_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL);";
CREATE table employee ("_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL, "
+ "fullName TEXT NOT NULL, "
+ "idCompany INTEGER NOT NULL, "
+ "FOREIGN KEY(idCompany) REFERENCES company (_id));";
When I run this query on my android app I get the following error:
05-09 22:35:23.170: E/AndroidRuntime(10920): FATAL EXCEPTION: main
05-09 22:35:23.170: E/AndroidRuntime(10920): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ej.ej/com.ej.ej.controlador.AplicacionActivity}: java.lang.IllegalArgumentException: column '_id' does not exist
If I run the same query but with select *:
mCursor = conexion.getDatabase().rawQuery("SELECT * FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idEmployee=company._id) ORDER BY employee.name", null);
No problem I get, it works fine. But since in my schema I have name for company and name for employee I need to differentiate both.
I tried doing this query using cmd and adb commands and it works. I really don't get why the error!!
EDITED: I made it work, as #HalR suggested in the query (dont know why) I have to retrieve the ids. So now I have:
mCursor = conexion.getDatabase().rawQuery("SELECT company._id, employee.name as employee, company.name as company FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
But I had one more issue and it wasnt in the query, it was on my ActivityFragment (thanks to #Hoan Nguyen, he made me see this part of the code again):
Listing my employees, I was getting the name of my employee and the idCompany. Don't know why, but this was looking for the _id of Company instead of idCompany of Employee.
String[] from = new String[] { "name", "idCompany"};
int[] to = new int[] { R.id.textViewNombreIzq, R.id.textViewNombreCent };
ListView lvEmployee = (ListView) view.findViewById (android.R.id.list);
ListClientsCursorAdapter notes = new ListClientsCursorAdapter(context, R.layout.activity_file_client, mCursorEmployee, from, to, 0);
lvEmployee .setAdapter(notes);
I just changed:
String[] from = new String[] { "name", "idCompany"};
For:
String[] from = new String[] { "employee", "company"};
And now is fine. Thanks to all, for your help I really apreciated :).
first, I in your CREATE TABLE employee statement you used the lable full name as a column label. If it is not a typo here, please change it to something like full_name. you can't just use spaces in column labels this way.
second, use this query string:
SELECT employee.name, company.name FROM employee INNER JOIN company ON (employee.idCompany=company._id) ORDER BY employee.name. Notice the ON expression. it's employee.idCompany not employee.idEmployee.
fix those first, and let me know if the error still exists.
I think you want this:
mCursor = conexion.getDatabase().rawQuery("SELECT employee.idCompany, employee.name, company.name FROM employee "
+ " INNER JOIN company "
+ " ON (employee.idCompany=company._id) ORDER BY employee.name", null);
Note: You need to make sure you specify the column name you are comparing in the section just after the SELECT.
Actually you don't need to name your column as _id in your table. for a example, you can create column as company_id in your company table and when you write your query, you can specify this column as below.
select company_id as _id, name from company.

how to modify an item's value in a SQLite?

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

SQLite Database Problem while delete

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

Categories

Resources