Android SQL Update statement - android

Can anyone tell me where I am going wrong with this SQL Update statement please?
SQLiteDatabase hashDB = openOrCreateDatabase(HASH_DB, MODE_PRIVATE, null);
hashDB.execSQL("CREATE TABLE IF NOT EXISTS " + HASH_TABLE1 + " (FileName VARCHAR, Hash VARCHAR);");
ContentValues updateFilesTable = new ContentValues();
updateFilesTable.put("Hash", hash);
hashDB.update(HASH_TABLE1, updateFilesTable, "FileName" + "=" + file, null);
file and hash are both Strings and I know they have the correct data in them, the records I am trying to update definitely exist in the database. HASH_TABLE1 also points to the correct table.
Many Thanks
Matt

You aren't quoting the file string. You want this line to read:
hashDB.update(HASH_TABLE1, updateFilesTable, "FileName = ?", new String[] { file });

Related

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.

android sqlite update row with like

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

Android crash when delete record

in a table SQLite. I have a list of strings that I see is in a listview by button I delete each record.
But if for example in the written record and the word "caffè" everything works fine, but if it is written the word " caffe' "the app crashes why?
thanks
String nome = tv.getText().toString();
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(NomeTable.TABLE_NAME, NomeTable.NOME_CAT + "='" + nome_cat + "'", null);
db.close();
finish();
This is because the ' is a special character in SQL.
So you end up with ='caffe'' which is invalid due to double ''.
You want to instead use the whereArgs param as well.
db.delete(NomeTable.TABLE_NAME, NomeTable.NOME_CAT + "= ?", new String[]{nome_cat});
That will escape your ' character for you and shouldn't mess you the SQL.
I would think nome_cat contains some symbols not alowed by the SQL syntax. You might want to use SQLiteQueryBuilder to build your query.

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

Insert null in Sqlite table

I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}

Categories

Resources