The SQL query statement LIKE binding parameter problem resolution in Android (sqlite database)

  • 2020-06-01 11:01:31
  • OfStack

Considering the security of the database, it is not easily injected by SQL. When executing the query statement, 1 generally does not use the directly spliced statement, but the method of parameter passing. Then, when you use the method of parameter passing, you find that it is easy to have a problem when you query the data in like mode.

Error case:

String myname = "abc";
String sql = "select * from mytable where name like '?%'";
Cursor cursor = db.rawQuery(sql, new String[]{myname};

The following error is shown:
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, the? The number is not identified, so new String[]{myname} cannot replace sql? Number. ? What is the reason that the number is not identified? There are single quotation marks outside the number, but in sql the value of the like statement and the % number need to be enclosed in quotation marks.

In order to solve sql? The number cannot be identified and must be removed. Right? The % sign also needs to be removed. So, you have to replace it in the back? Add a % sign to the parameter of.

So, the right case is:


String myname = "abc";
String sql = "select * from mytable where name like ?";
Cursor cursor = db.rawQuery(sql, new String[]{myname+"%"};

One might ask why you don't add quotes, because the argument instead? Automatically replaced as a string.


Related articles: