Because of the security of the database, it is not easy to inject SQL, when executing query statements, we usually do not use the direct stitching statements, but instead use the method of parameter passing. Then, when using the method of parameter passing, it is found that it is easy to have a problem when querying data by using the like mode.
Error Case:
Copy CodeThe code is as follows: String myname = "abc";
String sql = "SELECT * from MyTable where name is like '?% '";
cursor cursor = db.rawquery (sql, new String[]{myname};
The following error is prompted for the run:
Copy CodeThe code is as follows: Java.lang.IllegalArgumentException:Cannot bind argument at index 1 because the index was out of range. The statement has 0 parameters.
According to the error message, the number in the SQL statement is not recognized, so that new string[]{myname} cannot replace the number in SQL. The reason why the number is not recognized is that there is a single quote, but in SQL the value of the like statement and the% number need to be surrounded by quotation marks.
In order to solve the SQL in the number of unrecognized, you must remove the quotation marks, then the% number also needs to be removed. So, you have to add the% number in the back of the parameter instead of the? number.
So, the correct case is as follows:
Copy CodeThe code is as follows:
String myname = "abc";
String sql = "SELECT * from MyTable where name is like?";
cursor cursor = db.rawquery (sql, new string[]{myname+ "%"};
Android Android SQL query statement like binding parameter Problem solving method (SQLite database)