SQL injection attacks are introduced to Web applications by constructing special input as parameters. These inputs are mostly combinations in SQL syntax, attackers can execute SQL statements to perform the operations they want. The main reason is that the program does not carefully filter user input data, resulting in illegal data intrusion into the system.
The prepareStatement method is a simple and effective method to prevent SQL injection.
Differences between preparedStatement and statement
1. preparedStatement is a sub-Method of statement.
2. preparedStatement can prevent SQL Injection Problems
3. preparedStatement: It can pre-compile the SQL statements it represents to reduce the pressure on the server.
Example:
public User find(String username, String password) {Connection conn = null;PreparedStatement st = null;ResultSet rs = null;try{conn = JdbcUtils.getConnection();String sql = "select * from users where username=? and password=?";st = conn.prepareStatement(sql); st.setString(1, username);st.setString(2, password);rs = st.executeQuery(); //if(rs.next()){User user = new User();user.setId(rs.getString("id"));user.setUsername(rs.getString("username"));user.setPassword(rs.getString("password"));user.setEmail(rs.getString("email"));user.setBirthday(rs.getDate("birthday"));return user;}return null;}catch (Exception e) {throw new DaoException(e);}finally{JdbcUtils.release(conn, st, rs);}}