0

I created this parametric query that works perfectly. Now when a string is passed with an apex, I get this error

SQLiteException: near "'%'":

thi is the query

String sql = "SELECT titolo, icona, colore, tipo, identificativo, dato_campo FROM table " +
            "WHERE titolo LIKE '%" + parametro + "%' " +
            "OR dato_campo LIKE '%" + parametro + "%' GROUP BY identificativo";

if parametro It is a string of this type stringa', i get the error.

How can I fix?

1
  • please add your complete crash log Commented Jul 25, 2016 at 19:15

2 Answers 2

2

Problem is that your String has a single quote characters which breaks your SQL Query String.

Simulating parametro == test01 - OK

"SELECT titolo, icona, colore, tipo, identificativo, dato_campo FROM table WHERE titolo LIKE '%test01%' OR dato_campo LIKE '%test01%' GROUP BY identificativo";

Simulating parametro == stringa' NOK

"SELECT titolo, icona, colore, tipo, identificativo, dato_campo FROM table WHERE titolo LIKE '%stringa'%' OR dato_campo LIKE '%stringa'%' GROUP BY identificativo";

As you can see, your string is producing '%stringa'%' which is invalid for a SQL query.

You should escape that character ' during your query to something like: %stringa''%'.

So, you can add something as follows before creating your Query String:

parametro = parametro.replaceAll("\'","''");
String sql = "SELECT titolo, icona, colore, tipo, identificativo, dato_campo FROM table " +
        "WHERE titolo LIKE '%" + parametro + "%' " +
        "OR dato_campo LIKE '%" + parametro + "%' GROUP BY identificativo";

This is a support about the issue that your are facing now... As Gabe Sechan mentioned on the other answer, raw queries should be discouraged.

UPDATE

Safe way to run your query is:

String paramentro = "stringa'";
Cursor cursor = db.query("tablename", new String [] {"titolo", "icona", "colore", "tipo", "identificativo", "dato_campo"}, "titolo LIKE ? OR dato_campo LIKE ?", new String[]{"%"+paramentro+"%", "%"+paramentro+"%"}, "identificativo", null, null, null);
Sign up to request clarification or add additional context in comments.

Comments

1

Don't write SQL queries like this using concatenation. It leaves you wide open to SQL injection attacks. Instead, use bound parameters. Not only will this make your queries more efficient, they prevent SQL injection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.