android sqlite update row with like - android

I'm working sqlite.i wrote one function witch must update row with some values
this is a my source
public void updateLoanId (long id, String productId){
ContentValues values = new ContentValues();
values.put("LoanAnalisysID", id);
db.update(LoanAnalysisGraph_Table, values, "ViewId like " + productId + "%", null);
}
i try to update LoanAnalysisGraph_Table table by ViewId.when i run program i have syntax error near %
i don't know what is a wrong in my syntax
if anyone knows solution please help me .thanks

We have to enclose the productId in between single quotation. So change your update method like below
db.update(LoanAnalysisGraph_Table, values, "ViewId like '" + productId + "%'", null);

Related

SQLite - Match results based on string value issue

I'm currently having an issue with my SQL Lite code with regards to counting matching results. In my application the user will have the ability to add a new folder and give it a name. Before the folder is added to the application my code will check to see if a folder with the same name already exists if so it will prompt the user.
When using my code below I receive an error informing me the column doesn't exist. If I remove everything past WHERE then it works perfectly and counts every record within the table.
I've reinstalled the application and changed the database version so that its completely clean, just to make sure. I'm certain its only something very minor I'm missing.
public int countMatchingFolders (String folderName){
String countQuery = "SELECT * FROM " + Primary_Table + " WHERE " + Col_FolderName + " = " + folderName;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
Error message I'm receiving
android.database.sqlite.SQLiteException: no such column: testFolder (code 1): , while compiling: SELECT * FROM Folder_Table WHERE Col_FolderName = testFolder
Any assistance to help with the issue would be greatly appreciated.
The error is because the string value doesn't have quotes around it, so it is treated as a table name instead of a string. You should use a bound query argument to fix this. Bound arguments also prevent SQL injection attacks:
String countQuery = "SELECT * FROM " + Primary_Table + " WHERE " + Col_FolderName + " = ?";
Cursor cursor = db.rawQuery(countQuery, new String[]{folderName});
Note that you can do "SELECT COUNT(*) as row_count" ... to let the database engine count the number of records more efficiently.

How to write SQL statement containing 2 conditions in 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.

Replace function in SQLITE

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.

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.

sqlite db update

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

Categories

Resources