JDBC-防止sql注入漏洞
使用预编译可有效防止sql的注入漏洞。
原因:在statement中不能够有效的防止sql的注入漏洞,在于用户传入参数的时候可能会传入一些特殊字符,比如单引号' ' ,或者是-- 这种会影响到我们的sql语句.
所以使用预编译中的占位符,也就是?,可以有效的处理这一问题.
public class Prepared { @Test public void papa(){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try{ //注册驱动 // Class.forName("com.mysql.jdbc.Driver"); //建立连接 // conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user","root","dumy"); conn =JDBCUtils.getConnection(); //编写sql代码 //String sql = "select * from administer where id = ?"; String sql = "select * from administer where username = ? and password =?"; //预编译 pstmt = conn.prepareStatement(sql); //给? 赋值 pstmt.setString(1, "ddd"); pstmt.setString(2, "123"); rs= pstmt.executeQuery(); while(rs.next()){ System.out.println("登录成功"); } }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.release(pstmt, conn, rs); } } }
The above is the detailed content of How to prevent sql injection in jdbc?. For more information, please follow other related articles on the PHP Chinese website!