Passing parameters to a JDBC PreparedStatement

后端 未结 6 709
星月不相逢
星月不相逢 2020-11-28 11:45

I\'m trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consis

相关标签:
6条回答
  • 2020-11-28 12:20

    You can use '?' to set custom parameters in string using PreparedStatments.

    statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
    statement.setString(1, userID);
    ResultSet rs = statement.executeQuery();
    

    If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.

    0 讨论(0)
  • 2020-11-28 12:26

    If you are using prepared statement, you should use it like this:

    "SELECT * from employee WHERE userID = ?"
    

    Then use:

    statement.setString(1, userID);
    

    ? will be replaced in your query with the user ID passed into setString method.

    Take a look here how to use PreparedStatement.

    0 讨论(0)
  • 2020-11-28 12:29

    The problem was that you needed to add " ' ;" at the end.

    0 讨论(0)
  • 2020-11-28 12:35

    There is a problem in your query..

       statement =con.prepareStatement("SELECT * from employee WHERE  userID = "+"''"+userID);
       ResultSet rs = statement.executeQuery();
    

    You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId

    Replace it with: -

       statement =con.prepareStatement("SELECT * from employee WHERE  userID = :userId");
       statement.setString(userId, userID);
       ResultSet rs = statement.executeQuery();
    

    Or, you can use ? in place of named value - :userId..

       statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
       statement.setString(1, userID);
    
    0 讨论(0)
  • 2020-11-28 12:37

    You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:

    statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
    statement.setString(1, userID);
    

    There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.

    0 讨论(0)
  • 2020-11-28 12:41

    Do something like this, which also prevents SQL injection attacks

    statement = con.prepareStatement("SELECT * from employee WHERE  userID = ?");
    statement.setString(1, userID);
    ResultSet rs = statement.executeQuery();
    
    0 讨论(0)
提交回复
热议问题