Android Android SQL query statement like binding parameter Problem solving method (SQLite database)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.