0

I am trying to get column info from a cursor, and getting a frustrating error. I want to select all columns containing $SEARCH. Here is the code:

Bundle b = getIntent().getExtras();
        SEARCH = b.getString("searchtext");
        Cursor c = mDBHelper.getReadableDatabase().query("table", null, "name="+ SEARCH, null, null, null, null);

For some reason, the cursor is throwing a runtime exception. here is the error:

12-30 03:55:00.357: E/AndroidRuntime(1302): Caused by: android.database.sqlite.SQLiteException: near "CAP": syntax error: , while compiling: SELECT * FROM kroger WHERE name=john

Not sure why this is happening, there's probably a very simple error in my code, but I'm not sure what it is. THanks for your help!

1 Answer 1

3

"name="+SEARCH will become name=CAP, which isn't a valid SQL expression. The naïve solution is to wrap the term in single-quotes:

"name='" + SEARCH + "'"

But this is subject to SQL injection attacks. Use the argument-passing facilities to pass the search term in an injection-free manner:

query("table", null, "name=?", new String[] {SEARCH}, null, null, null);
Sign up to request clarification or add additional context in comments.

7 Comments

Why is the first suggestion subject to attack and not the second?
@barry: Say the user searches for CAP'; DROP TABLE table; --. With the first solution, this would become the following SQL: SELECT * FROM table where name='CAP'; DROP TABLE table; --'. With the second solution, the SQL remains SELECT * FROM table WHERE name=?, with the ? bound to the bogus search term as a string value, semantically, not syntactically, so the search would fail in a benign manner.
@marcelocantos Thanks for that, very interesting. But wouldn't the second version eventually result in the same sql as the first?
@barry: No. The variable bindings are applied after the SQL has been parsed. The ? is a placeholder for a value, not a chunk of SQL.
@barry: It's an internal representation that differs from one engine to the next. Some systems (e.g., SQL Server) convert to an AST, others (Oracle, I think) go straight to an execution tree. I don't know what SQLite does, but suspect it takes a relatively directly path to p-code suitable for its internal VM. The point is that by the time the bindings get applied the original SQL syntax is long gone, so it is meaningless to talk about what the query ends up looking like after variables are bound.
|

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.