sqlite.SQLiteException: near "s": syntax error: because of apostrophe - android

The song name that I want to insert it into my table contains a " ' " (apostrophe )so , there is an error when the request is excuted. How can I fix it
Cursor pid = mDB.rawQuery("select Id FROM MusicPlayer WHERE "Path ='" + sname + "';", null);
I am getting sname runtime so .. sname=/mnt/sdcard/Now Thats What I Call Music 85 [Bubanee]/16 - Let's Get Ready To Rhumble (100% Radio Mix) - PJ & Duncan.mp3
I get below error..
android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling: SELECT Id FROM MusicPlayer WHERE Path ='/mnt/sdcard/Now Thats What I Call Music 85 [Bubanee]/16 - Let's Get Ready To Rhumble (100% Radio Mix) - PJ & Duncan.mp3';
Because sname contain let's word with ' which gives me error.

In theory you could escape ' as '' in SQL.
However, it's better to use variable binding. Replace the string literals in SQL with ? and supply corresponding number of Strings in an array:
Cursor pid = mDB.rawQuery("select Id FROM MusicPlayer WHERE Path = ?;",
new String[] { sname });

you can get details for Sting within comma or someother means use like this cursor.
Cursor cursor = odb.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_ITEM + "=?;", new String[]{comboname});
Thanks laalto sir your answer is work perfectly.

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.

Saving webview geturl and getitle in Sqlite database. Problem with syntax error apostrophe '

When im saving webview.getTitle (); in Sqlite database, if in title has apostrophe ('), then i got error -
android.database.sqlite.SQLiteException: near "at": syntax error (code 1): , while compiling: INSERT INTO Favorite VALUES('4 madhab bid'at tavassul', 'file:///android_asset/web/akaid/4maddhab/4.htm' );
My code like this
mysql objcon = new mysql(this, null, null, 1);
SQLiteDatabase db = objcon.getReadableDatabase();
db.execSQL(
"INSERT INTO Favorite VALUES('"
+ txtnombre.getText()
+ "', '"
+ txtlink2.getText()
+"' );"
);
How to solve this problem?
There is a single quote embedded within txtnombre.getText() : '4 madhab bid'at tavassul'. This causes SQLite to wrongly consider that this quote marks the end of the first value to insert.
To avoid that, you could consider manually doubling the single quotes :
db.execSQL(
"INSERT INTO Favorite VALUES('"
+ txtnombre.getText().replaceAll("'","\''")
+ "', '"
+ txtlink2.getText().replaceAll("'","\''")
+"' );"
);
I would recommend using bind parameters. With this option, your database driver handles escaping behind the hood :
q = "INSERT INTO Favorite VALUES(?, ?)";
t1 = txtnombre.getText();
t2 = txtlink2.getText();
db.rawQuery(q, new String[] { t1, t2 });
Finally, another approach in Android would be to use native method sqlEscapeString(), which is primarily built for this purpose.
Also, as commented by pskink, using insert() would better fit your use case than raw SQL.

error occurs when updating a table in sqlite

String updateQuery = "UPDATE Bookdetails SET lastchapter = " + test + " WHERE bookpath=" +sentFilename;
db.execSQL(updateQuery);
Error:
03-04 13:36:23.997: I/System.out(9722): android.database.sqlite.SQLiteException:
near "/": syntax error: , while compiling: UPDATE Bookdetails SET lastchapter =
mukund WHERE bookpath=/mnt/sdcard/Download/What's so great about the doctrine of
grace.epub errors happens
the error is posted above
My table contains the field id, bookpath and lastchapter, book path contains the values
/mnt/sdcard/Download/What's so great about the doctrine of grace.epub
/mnt/sdcard/Download/1b4fdaac-f31d-41e8-9d15-26c9078d891f.epub
/mnt/sdcard/Download/Commentary on Romans.epub
and lastchapter contains the values nothing nothing nothing
id contains 1 2 3
why is the error occurring at "/" there is no hash in my update query it is only there at string which stores bookpath? Is this an error?
String literals in SQL need to be in '' quotes.
However, it's better to use ? placeholders for literals like this:
String updateQuery = "UPDATE Bookdetails SET lastchapter=? WHERE bookpath=?";
db.execSQL(updateQuery, new String[] { test, sentFilename });
I believe your lastchapter & bookpath is of type String (TEXT). Hence when you are adding or updating it's value you should always use ' ( Single cot ) around it. Change your query to this,
String updateQuery = "UPDATE Bookdetails SET lastchapter ='" + test + "' WHERE bookpath='" +sentFilename + "'";
db.execSQL(updateQuery);
However, Direct Execution of SQL query is not advisable at developer.android.com hence you can use alternative way like below code,
String updateQuery = "UPDATE Bookdetails SET lastchapter=? WHERE bookpath=?";
db.execSQL(updateQuery, new String[] { test, sentFilename });

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.

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.

Categories

Resources