How to use prepared statement for sql? - java

I'm trying to have an SQLite database in android but I have a problem with that:
I'm trying to update the text value in the "response" column with id 0. The first problem I had was that the string I was using for the update used an apostrophe (') and it had syntax errors because sql closes the string with an '. So I now am using a prepared sql statement for that. The problem now is that the long that is returning gives a -1, so that means that no rows were effected. So how can I update my current string to the row with id=0?
Note: the first string also has an ' but was added using the addData funtion and it didn't give any errors just using db.insert, is that the problem, should I replace all my code with prepared statements?
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public long updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
String sql = "UPDATE json_response SET response=? WHERE ID='0'";
SQLiteStatement statement = db.compileStatement(sql);
statement.bindString(1, newName); // matches second '?' in sql string
long rowId = statement.executeInsert();
return rowId;
}

I have not used prepared statements much so I can't say why that is not working, but why not use the db.update() method? It takes ContentValues as an argument similar to tour addData() method. Give this a shot.
public int updateData(String newName){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("json_response",newName);
int rows = db.update(TABLE_NAME, cv, "ID=0", null);
return rows;
}
[EDIT] update() returns an integer representing the number of rows affected instead of which row was affected. Keep that in mind as your variable name rowId implies that is not what you are looking for.
[EDIT 2] And no, there is no problem with the addData() method that I can see. The apostrophe that was added did not cause an error because ContentValues parameterizes the string values before adding them into the database. Basically, all SQL-like syntax will be ignored when inserting values, which is great for security reasons.

The problem is, I think, that WHERE ID='0' will always fail; what you want is WHERE ID=0

Related

Android SQLite, update specific field from specific row

I am trying to update a specific column in my record within SQLite - the object has various attributes, but I just want to update a single field within that row. Here are my codes:
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(EMAIL, email);
args.put(IS_FAV, isFavorite);
int i = db.update(TABLE_FAVORITES, args, EMAIL + "=" + email, null);
return i > 0;
}
I am using the email for my where clause, i.e update record from favorites, set isFavorite to (given value) where email is (passed in value).
There is a problem with my query, which was caught by logcat, as shown below
android.database.sqlite.SQLiteException: near "#sjisis": syntax error (code 1): , while compiling: UPDATE Favorites SET email=?,isFavorite=? WHERE email=sjkshs#sjisis.com
Can anyone help me identify what is wrong with my codes to produce this error?
P.S my FavoriteObject class has other attributes other than just email and isFavorite, but in this case I am not trying to update them at all
Try to make email in where clause be argument too, i try to change your code but didn't test yet :
public boolean updateFavorite(String email, int isFavorite){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values= new ContentValues();
values.put(EMAIL, email);
values.put(IS_FAV, isFavorite);
//add arguments for where clause
String[] args = new String[]{email};
int i = db.update(TABLE_FAVORITES, values, "EMAIL=?", args);
return i > 0;
}
Looks like it's complaining about the email address, perhaps the #.
try
int i = db.update(TABLE_FAVORITES, args, EMAIL + "= ' " + email + "'", null);
ie. single quotes around the email address.

Update multiple rows in Android sqlite

I have table contains columns id, name, profession, age, hobby, country, sex. Now I want to update the fields where sex is female and age is 30. All the fields are text (String). First, I am counting all the rows then running a loop to update the rows. Loop is running as per the total rows but rows are not updated... WHY? Where I have done the mistake? Here is my code:
METHODS FOR ANDROID SQLITE DATABASE QUERY:
public void updateUser(String newProfession, String newCountry, String sx, String ag) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE "+TABLE_USER+" SET "+KEY_PROFESSION+"='"+newProfession+"', "+KEY_COUNTRY+"='"+newCountry+"' WHERE "+KEY_SEX+"='"+sx+"' AND "+KEY_AGE+"='"+ag+"'";
Cursor cursor = db.rawQuery(query, null);
cursor.close();
db.close();
}
public int countAll() {
String countQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
db.close();
return cnt;
}
CALLING THE METHODS
public void updateUsersClicked(View view) {
int allData = db.countAll();
for (int i = 0; i < allData; i++) {
db.updateUser("SENIOR ENGINEER", "CANADA", "female", "30");
System.out.println("T H I S I S T H E R E S U L T: " + i);
}
}
Use execSQL() and not rawQuery() for updates.
rawQuery() just compiles the SQL and requires one of the moveTo...() methods on the returned Cursor to execute it. execSQL() both compiles and runs the SQL.
Also consider using ? parameters with bind args in your SQL to avoid escaping special characters and being vulnerable to SQL injection.
You don't need to do the for loop
a single QSL "Update" query is enough if you want to update All the female with age 30.
If you are new to SQL you can view a simple example here:
Simple SQL Update example
If you want to do something else - please edit your question

How to delete from SQL Database

I am trying to write code to delete a transaction from an SQL database. The function below adds a deposit and another deletes it from the SQL database. When I try running it, it leads to an SQLLiteException from this line:
TransactionDAO.removeTransaction(int, String) line: 154
public void addDeposit(int accountID, String transName, long efDate,
double amount) {
ContentValues tran = new ContentValues();
tran.put(SQLHelper.COLUMN_ACCOUNTID, accountID);
tran.put(SQLHelper.COLUMN_TRANSNAME, transName);
tran.put(SQLHelper.COLUMN_ENTEREDTIMESTAMP, Calendar.getInstance()
.getTimeInMillis());
tran.put(SQLHelper.COLUMN_EFFECTIVETIMESTAMP, efDate);
tran.put(SQLHelper.COLUMN_AMOUNT, amount);
tran.put(SQLHelper.COLUMN_COMMITTED, 1);
database.insert(SQLHelper.TABLE_TRANSACTION, transName, tran);
}
public void removeTransaction(int accountID, String transName) {
ContentValues tran = new ContentValues();
database.delete(SQLHelper.TABLE_TRANSACTION, transName, null);
}
I really have no idea how to solve this problem. Im confused on how to find the exact row in an SQL database. That is probably the reason for the error.
According to public int delete (String table, String whereClause, String[] whereArgs), where the second argument is a where clause, you should use
database.delete(SQLHelper.TABLE_TRANSACTION, String.format("%s=?", SQLHelper.COLUMN_TRANSNAME), {transName});

SQLite query - date reserved word?

Am just curious, is date a reserved word i SQLite? I have a column which is named date, and trying to run this query:
DELETE FROM cases WHERE date <= date('now','-1 day')
By doing this:
String query = "DELETE FROM cases WHERE date <= date('now','-1 day')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
But the cursor just gives me a false back, when calling moveToFirst. But in my database there are actually rows that are older than one day. Can anybody explain whats wrong here?
Thanks!
Yes it seems to be a reserved word.
look at: http://www.sqlite.org/lang_datefunc.html
date(timestring, modifier, modifier, ...)
It's strange to have a cursors form DELETE statement. Try to split the operation in
SELECT * FROM cases WHERE date <= date('now','-1 day')
then execute your checks
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
boolean found = cursor.moveToFirst();
if(found) {
int result = cursor.getCount();
Log.w("DeleteOldCases: ", "Result: " + Integer.toString(result));
db.close();
}
and then execute the DELETE part
DELETE FROM cases WHERE date <= date('now','-1 day')
This question is quite old but it deserves a proper answer.
No, date is not a reserved word.
The problem with your code is that you are using the method rawQuery() to delete from the table, which is not the way to do it.
rawQuery() should be used to return rows from the table in the form of a Cursor object.
Since your sql statement does not return any rows the method moveToFirst() returns false.
What you should use is the method delete() which returns the number of deleted rows:
int result = db.delete("cases", "date <= date('now', '-1 day')", null);

how to update a varchar in the sqlite database in java

I have a problem with to update a varchar in the sqlite database in java.
when I run this source, than I get a error.
I want String a to update to String b.
This is my source:
public void onClick (View v){
String a = "Test1";
String b = "Test2";
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, a, null);
db.close();
}
And this is my Error:
Error updating Level1=Test2 using update Game SET Level1=? WHERE Test1.
can someone help me?
Thanks!
I'm not 100% sure what you are trying to achieve, however, you added a as a where clause and did not provide any arguments, so consequently you got the SQL statement shown in the error.
From the API:
public int update (String table, ContentValues values,
String whereClause, String[] whereArgs)
This one works ...
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
ContentValues values = new ContentValues();
values.put("Level1", b);
db.update("Game", values, "Level1=?", new String[] {a} );
db.close();
... if this is the resulting SQL you want to execute:
update Game SET Level1=? WHERE Level1 = 'Test1'
update Game SET Level1=? WHERE Test1.
Where Test1 is.. what? Where is the conditional part of your update statement. It's expecting something like:
update Game SET Level1=? WHERE ColumnName='Test1'
Taken from this website:
If the UPDATE statement does not have a WHERE clause, all rows in the table are modified by the UPDATE. Otherwise, the UPDATE affects only those rows for which the result of evaluating the WHERE clause expression as a boolean expression is true.
A String on it's own is in no way a boolean expression.

Categories