Android SQL query statement like binding parameter Problem resolution (SQLite database) _android

Source: Internet
Author: User
Tags sql injection sqlite sqlite database

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.

Related Article

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.