Because of the security of the database, not easily SQL injection, the execution of query statements, generally do not use the direct stitching of the statement, but the use of parameter transfer method. Then, when using the method of parameter passing, it is found that a problem can easily occur when querying data using the like method.
Error Case:
Copy Code code as follows:
String myname = "abc";
String sql = "SELECT * from mytable where name like '?% '";
Cursor Cursor = db.rawquery (sql, new String[]{myname};
The run prompts the following error:
Copy Code code as follows:
Java.lang.IllegalArgumentException:Cannot bind argument at index 1 because the ' index is out of range. The statement has 0 parameters.
According to the error hint, what is in the SQL statement? number is not recognized, so that the new string[]{myname} cannot replace the SQL? number.? The reason why the number is not identified is estimated? An extra has single quotes, but in SQL, the value of the like statement and the% number need to be surrounded by quotes.
In order to solve the problem that the SQL number cannot be recognized, the quote number must be removed. So, you have to add the% number in the back of the argument instead of the number.
So the correct case is as follows:
Copy Code code as follows:
String myname = "abc";
String sql = "SELECT * from mytable where name like?";
Cursor Cursor = db.rawquery (sql, new string[]{myname+ "%"};
Some people may ask why you don't need to add quotes, because the arguments are automatically replaced by strings when they are substituted for the number.