Research on preventing SQL injection (Java code implementation)

Source: Internet
Author: User

 

There are two methods: one is to judge the variables obtained by login with special characters

One is to use preparedstatement for query during login, which can be effectively used for SQL injection.

 

Method 1

Sqlstring. Java

  1. Package com. Test. util;
  2. Public class sqlstring {
  3. Public static Boolean SQL _inj (string Str ){
  4. String inj_str = "': And: Exec: insert: select: delete: Update: Count: *: %: CHR: Mid: MASTER: truncate: Char: declare:;: or: -: + :,";
  5. String inj_stra [] = inj_str.split (":");
  6. For (INT I = 0; I <inj_stra.length; I ++ ){
  7. If (Str. indexof (inj_stra [I])! =-1 ){
  8. Return false;
  9. }
  10. }
  11. Return true;
  12. }
  13. }

Use the following statement when calling:

Boolean F = sqlstring. SQL _inj (username );

 

PS: I have read the above Code on the Internet. They use the separator "|", but I found that string inj_stra [] = inj_str.split ("| "); all the characters are separated. instead of splitting strings, they are split into characters. I use jdk1.5. I don't know if it is a Java version, the example of the jdk1.5 API is separated by ":", so I can use this symbol to split each string.

 

The second method is to use preparedstatement during query.

  1. SQL = "select * from Admin where username =? And Password =? ";
  2. Preparedstatement psmt = con. preparestatement (SQL );
  3. Psmt. setstring (1, username );
  4. Psmt. setstring (2, password );
  5. Resultset rs = psmt.exe cutequery ();
  6. If (Rs. Next ){
  7. Rs. Close ();
  8. Con. Close ();
  9. Return false;
  10. }
  11. Else {
  12. Rs. Close ();
  13. Con. Close ();
  14. Return true;
  15. }

In this way, you can

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.