I'm facing an issue with SQLite in Android, I know the solution must be simple, but what I have done is not working !!
// Update a contact with a new name
public void updatename (String phone, String newname) {
newname = newname.replaceAll("'","\'");
String query = "UPDATE contacts SET name = '"+newname+"' WHERE phone = '"+phone+"'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
//db.close();
}
the replace function is not working !!
Use update() to map your strings into placeholders, and Sqlite will escape the strings so that the final command is always valid.
You should always be doing this for every command.
Use PreparedStatement, and should never do the quoting stuff yourself, just unnecessary trouble:
PreparedStatement pstmt = con.prepareStatement("UPDATE constacts SET name = ? WHERE phone = ?");
pstmt.setString(1, "foo")
pstmt.setString(2, '123")
SQL does not use a backslash for escaping.
In SQL string literals, quotes are doubled, so you'd need to replace ' with ''.
But it would be a better idea to use parameters:
String query = "UPDATE contacts SET name = ? WHERE phone = ?";
db.execSQL(query, new Object[]{ newname, phone });
Use Prepared Statements. This sanitizes the input for you before calling the sql command.
How do I use prepared statements in SQlite in Android?
Related
I made an app in eclipse for android where you can fill in a person's information like name, email, adress, etc. In this app I need to include a search-button, which will search for a person that is saved in the database when one or more pieces of information are known. E.g. when I only remember the email-adress of a person who is saved in the database, I need to be able to find that person by searching for a matching email. This is the code I used for doing so:
public Person getPerson(String naam, String adres, String email, String geslacht,
String leeftijd, String geboortedatum){
SQLiteDatabase db= this.getReadableDatabase();
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ? OR adress = ? "
+ "OR email = ? OR gender = ? OR age = ? OR birthday = ?",
new String[]{naam==null?"'":naam, adres==null?"'":adres,
email==null?"'":email, geslacht==null?"'":geslacht,
leeftijd==null?"'":leeftijd, geboortedatum==null?"'":geboortedatum});
if(curs!=null)
curs.moveToFirst();
The reason I changed the args[] when it included a null-value is that otherwise the rawQuery won't work. This code however, does not return the person I was searching for, but it simply returns the very first person in the database.
When simplifying the code by making the query search for a persons name only it actually does return the person with that name:
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ?", new String[]{naam});
if(curs!=null)
curs.moveToFirst();
What is wrong with the first rawQuery and why doesn't it return the person I'm looking for, but simply the first person in the database, whereas the second rawQuery does return the right person?
I guess the problem is with the OR. Could you try AND and see ? Because OR is usually means optional. What i mean by optional is, you are telling sql engine to return the person with any of those attributes it matches too. So you are not restricting but giving many possibility abd OR is ending up with many users and therefore its getting the first one. Dont use OR. Try creating a query that returns a unique result you want.
public Person getPerson(String naam, String adres, String email, String geslacht,
String leeftijd, String geboortedatum){
SQLiteDatabase db= this.getReadableDatabase();
Cursor curs=db.rawQuery("SELECT * FROM personen WHERE name = ? OR adress = ? "
+ "OR email = ? OR gender = ? OR age = ? OR birthday = ?",
new String[]{naam==null?"'":naam, adres==null?"'":adres,
email==null?"'":email, geslacht==null?"'":geslacht,
leeftijd==null?"'":leeftijd, geboortedatum==null?"'":geboortedatum});
if(curs!=null)
if (curs.moveToFirst()){
while(curs.hasNext){
//Your code, this will return all the rows of your sql,use curs.next() to get a row
}
I am having trouble with inserting a string using sqlite in an android app,
I tried,
query = "INSERT OR REPLACE into table(_id, text) VALUES ("+data.get(i).id+", '"+data.get(i).text+"')";
MyClass.db.execSQL(query);
If my string looks like,
'I'm an android developer'
App crashes here, here is logcat result,
Caused by: android.database.sqlite.SQLiteException: near "m": syntax error: , while compiling: INSERT OR REPLACE into table (_id, text) VALUES (4, '"I'm an android developer"' )
I think it assumes that, my query ends here
'"I'
please help me to insert any case of string, either it contains single or double quotes like,
"I'm an "android" developer"
Without any hardcoding or anything you can directly insert with using ContentValues like below..
ContentValues values = new ContentValues();
long retvalue = 0;
values.put("_id", id_here);
values.put("text", your_text_here);
retvalue = MyClass.db.insertWithOnConflict(table, null, values, CONFLICT_REPLACE);
If you are using normal insert statement and if you have any value which contains single quote in it, then you might face a weird issue like this. So,try this..
String insert_info = "INSERT OR REPLACE INTO table(_id,text) VALUES (?,?)";
SQLiteStatement stmt = db.compileStatement(insert_info);
stmt.bindString(1, ""+data.get(i).id);
stmt.bindString(2, ""+data.get(i).text);
stmt.execute();
Multiple options:
Use ContentValues with SQLiteDatabase.insert()
Use variable binding, e.g.
db.execSQL("INSERT INTO table(_id, text) VALUES(?,?)", new String[] { idValue, textValue });
Escape the ' in strings. The SQL way to escape it is '' and you can use DatabaseUtils helpers to do the escaping.
To escape the " in Java strings, use \".
you must replace \' with \'\' in query string:
String getQuery(){
query = "INSERT OR REPLACE into table(_id, text) VALUES ("+data.get(i).id+", '"+getSqlValue(data.get(i).text)+"')";
MyClass.db.execSQL(query);
return query;
}
String getSqlValue(String input){
return input.replace("\'","\'\'");
}
You can use " for skipping " in a string
I'm trying to delete a row in a table where I know the row exists. I tried:
final String s = "DELETE from %s where Name = '%s'";
String sql = String.format(s, GetTableName(), sListName);
Cursor cr= GetUserDb().GetSQLiteDb().rawQuery(sql, null);
and I tried:
String sWhere = String.format("Name = '%s'", sListName);
long lRowsUpdated = GetUserDb().GetSQLiteDb().delete(GetTableName(), sWhere, null);
** sWhere >> Name = 'groceries' **
** sql >> DELETE from Lists where Name = 'groceries' **
There is no crash or logcat exception but the row is still not deleted. Is there something I'm missing? Maybe I have a lock on it somewhere else or I need to set certain permissions in my Manifest or something?
Use delete() from SqliteDatabase - this returns the count of affected rows. E.g. delete(tablename, "name=?", new String[] { aString } )
Try this:
SQLiteStatement stmt = db.compileStatement("DELETE FROM " + getTableName() + "WHERE Name=?");
stmt.bindString(1, sListName);
stmt.execute();
if the column you're trying to have your key by is sListName you should have delete where sListName = '%s' unless you have another column that is called Name that you are trying to delete, but if that isn't your primary key you might end up getting two rows in your delete.
You can always use the emulator and an adb shell and just go run the sqlite3 shell command and try your SQL statements. If you type yours in and get 0 rows affected, you know you're statement is messed up, not your java.
If you're not using any built in CurorAdapters or ContentProviders your primary key does not need to be named _ID, it can be named whatever. As for the type, in SQLite3, it's really just a suggestion on how to cast it, you can put whatever data in whatever column you want.
I am building a cursor for a select query. The WHERE section lookup value refers to a variable which is a path so it has several full stops in it.
The query doesnt like this and errors , the error says a col doesn't exist named with a name which is the lookup value i.e the path with stops in it. If I use the sqlEscape util on the variable it doesnt cause an error but the lookup fails.
Any suggestions please?
Without a bit of your code it is hard to say but I'm guessing you are putting your where clause together like this:
String value = "some.thing.or.other";
String where = "FIELD = " + value;
Try building a parameterized where clause instead
String value = "some.thing.or.other";
String where = "FIELD = ?";
SQLiteDatabase db = fDbOpener.getReadableDatabase();
Cursor results = db.query(TABLE_NAME, COLUMNS_LIST, where, new String[] { value }, null, null, null);
When you run the query method now, SQLite will substitute your value into the where clause specifically as a value - it won't try to interpret the value in any way so it can't mistake the full stops for syntax.
I am trying to update the database on the basis of incoming parameter but it is not updated.
i am using the following code:
public static void markFavoriteStation(String station, boolean favorite){
Log.d(AppConstants.TAG,"StationListDBIfc: +markFavoriteStation");
String Query = null;
mDb = bartDb.getWritableDatabase();
Query = "update stationlistTable set favorite ='1' where namewithabbr = '+station'";
mDb.rawQuery(Query, null);
Log.d(AppConstants.TAG,"StationListDBIfc: -markFavoriteStation");
}
I think you might have a malformed String definition. You should end the String before concatenating the "station" variable to it, like so:
Query = "update stationlistTable set favorite ='1' where namewithabbr = '" + station + "'";
I can't see any errors. I guess the SQL query has errors or the namewithabbr column doesn't contain what you expect. You should test it in the sqlite3 app.