I am having problem querying single quote while using the sql LIKE statement
this is my SQL query for searching the MUSIC file in the SD CARD.
final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String[] cursor_cols = {
MediaStore.Audio.Media.TITLE
};
where = MediaStore.Audio.Media.TITLE + " like ('%"+SomeSongTitle+"%')";
cursor = getContentResolver().query(uri, cursor_cols, where, null, null);
SomeSongTitle is some arbitrary input text that the a user input.
My Question is why when SomeSongTitle contains a single Quote(for example SomeSongTitle=don't), it crashes.
And How to fix it?
thankz for reading and hope to hear some solution from you guys =D. hehe
If you don't want to do String substitution you can use SQLiteDatabase.rawQuery to get your Cursor object. And then do something like:
String query = "select * from your_table_name where" + MediaStore.Audio.Media.TITLE + " like ('%?%')";
cursor = yourDB.rawQuery(query, new String[] {SomeSongTitle});
That should get around the quoting issue.
To fix it you need to replace the single quote with two single quotes. Try using something like...
SomeSongTitle = SomeSongTitle.replace("'", "''");
If you use bindings (?) for the argument(s) in the where clause, then you do not need and should not use any single quotes because the binding already takes care of that.
In particular, the second argument in a binding is an array of strings,
String[], providing one String for each ?. In the binding process, each of those Strings is treated by sql as if it has single quotes around it. Binding creates a compiled sql statement with variable substitution, so it is efficient to write your sql as a fixed String and binding rather than make a different statement each call.
You'll need to escape the single quote. There are much more sophisticated methods to do this, but an easy way to start is to simply to a find and replace in order to add a slash (\) before the quote mark so that it looks like this: (\').
You can read more about it SQL Injection. Specifically, look at the section on Mitigation.
Android's database API sits on top of sqlite. In its FAQ, you can see that to "escape" a single quote, you just use two single quotes. See here.
Related
I'm handling user data and store it to oracle which may contain "'", "''", or "'''".
I have try to use replaceAll() method to convert data but it output not my expected result.
try replaceAll() but not work
String sAddress1="";
sAddress1 = "ABC''S ROA'''D";
sAddress1 = sAddress1.replaceAll("'","''");
I expect the output of sAddress1 to be:
"ABC''''S ROA''''''D"
But the actual output is:
"ABC''S ROA''''D"
Your code works correctly. The problem is the persistence in your Oracle DB.
In which way are you storing it into the DB? Are you using native SQL? Are you using JPA/Hibernate?
Probably you are using a Native SQL, since the JPA/Hibernate options should handle the quoting for you.
Take a look to the text literials section in the Oracle documentation https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#sthref344
Or take a look to other answers about escaping single quoutes for Oracle DB
PL/SQL, how to escape single quote in a string?
Escaping single quote in PLSQL
Is there a way to specify a custom separator for the method groupConcatDistinct in JOOQ? There is a second parameter for the method groupConcat but this one returns multiple times the same values, which I don't want.
Thanks!
Okay I found the answer, with groupConcatDistinct the separator is chained and not a parameter. Like this groupConcatDistinct(...).separator(", ")
This is just an oversight in API design. I've created a feature request here:
https://github.com/jOOQ/jOOQ/issues/7956
As always when working with jOOQ and you encounter a missing feature, you can resort to using plain SQL templating. E.g.
Field<String> f = DSL.field(
"group_concat(distinct {0}, ', ')",
SQLDataType.VARCHAR,
MY_COLUMN
);
Is there a built-in method to escape a string for SQL? I would use setString, but it happens I am using setString multiple times in the same combined SQL statement and it would be better performance (I think) if the escape happened only once instead of each time I say setString. If I had the escaped string in a variable, I could re-use it.
Is there no way to do this in Java?
Current method, multi-source search. In reality they are three entirely different where statements including joins, but for this example I will just show the same where for each table.
String q = '%' + request.getParameter("search") + '%';
PreparedStatement s = s("SELECT a,b,c FROM table1 where a = ? UNION select a,b,c from table2 where a = ? UNION select a,b,c FROM table3 where a = ?");
s.setString(1, q);
s.setString(2, q);
s.setString(3, q);
ResultSet r = s.executeQuery();
I know this is not a big deal, but I like to make things efficient and also there are situations where it is more readable to use " + quote(s) + " instead of ? and then somewhere down the line you find setString.
If you use setString for a parameter (e.g. PreparedStatement.setString), there may well be no actual escaping required - it's likely that the data will be passed separately from the SQL itself, in a way that doesn't require escaping.
Do you have any concrete indication that this really is a performance bottleneck? It seems very unlikely that within a database query, the expensive part is setting the parameters locally...
Short answer: I wouldn't bother. It's best to do escaping at the last popssible moment. When you try to escape a string early and keep it around, it becomes much more difficult to verify that all strings have been escaped exactly once. (Escaping a string twice is almost as bad as not escaping it at all!) I've seen plenty of programs that try to escape strings early and then run into trouble because they need to update the string and then the programmer forgets to re-do the escape, or they update the escaped version of the string, or they have four strings and they escape three of them, etc. (I was just working on a bug where a programmer did HTML escapes on a string early, then decided he had to truncate the string to fit on a form, and ended up trying to output a string that ended with "&am". That is, he truncated his escape sequence so it was no longer valid.)
The CPU time to escape a string should be trivial. Unless you have a very large number of records or very big strings that are re-used, I doubt the savings would be worth worrying about. You'd probably be better off spending your time optimizing queries: saving a read of one record would probably be worth far more than eliminating 1000 trips through the string escape logic.
Longer answer: There's no built-in function. You could write one easily enough: Most flavors of SQL just need you to double any single quotes. You may need to also double backslashes or one or two other special characters. The fact that this can be different between SQL engines is one of the big arguments for using PreparedStatements and letting JDBC worry about it. (Personally I think there should be a JDbC function to do escaping that could then know any requirements specific to the DB engine. But there isn't so that's how it is.)
In any case, it's not clear how it would work with a PreparedStatement. There'd have to be some way to tell the PreparedStatement not to escape this string because it's already been escaped. And who really knows what's happening under the table in the conversation between JDBC and the DB engine: Maybe it never really escapes it at all, but passes it separately from the query. I suppose there could be an extra parameter on the setString that says "this string was pre-escaped", but that would add complexity and potential errors for very little gain.
Do not use org.apache.commons.lang.StringEscapeUtils.escapeSql(yourUnscapedSQL);
It does not escape characters like \
You can use StringEscapeUtils from Apache commons:
org.apache.commons.lang.StringEscapeUtils.escapeSql(yourUnscapedSQL);
Is there a Java library for escaping special characters from a string that is going to be inserted into an SQL query.
I keep writing code to escape various things, but I keep finding some new issue trips me up. So a library that takes care of all or most of the possibilities would be very handy.
EDIT: I am using MySQL (if that makes any difference).
Well... jdbc. Pass the strings as parameters, and don't append them to the query string
A little bit more research points me to this:
http://devwar.blogspot.com/2010/06/how-to-escape-special-characters-in.html
Which suggests to use apache.commons.lang.StringEscapeUtils, I will try this out
I know this is a long time thread, but using the commonslang library there is a method called escapeSql(String). Also using prepared statement automatically escape the offending SQL character.
I have a bind in the SQL query
SELECT * FROM users WHERE name LIKE '%?%'
the bind set the ?.
Now, if i want to search with like method everything work but if, without change the sql, i want to search the exact match i dont now how to do.
I tried some regexp int the textbox es:
_jon \jon\ [jon] and some others but nothing work properly.
Any ideas?
Change your query to
select * from users where name like '?'
If you want to do a wildcard match, put the wildcards as part of the string that you're binding to the variable. If you don't want to do a wildcard match, then don't.
Note that like and = have the same performance except when your wildcard character is first in the string (for example, '%bob') as in that case the query optimizer can't use indexes as well to find the row(s) that you're looking for.
you can't search an exact match if the sql contains % symbols, as they are wildcards. you'll need to change the sql to
select * from users where name = '?'
for an exact match
(you can also use select * from users where name like '?' but that's more inefficient)
What is keeping you from changing the SQL?
The Like condition is for 'similar' matches, while the '=' is for exact matches.