在选择使用Statement时,会产生SQL注入:
@Test public void testSave(){ String name = "a' or 1=1 or 1='"; String password ="123"; Connection conn = null; Statement st = null; ResultSet rs = null; conn = DBUtil.getCon(); //String sql = "select * from s_user where id=100"; try { st = conn.createStatement(); String sql = "select * from users where username='"+name+"'and password='"+password+"'"; System.out.println(sql); rs = st.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
这回显示登录成功。
但是如果使用PreparedStatement:
@Test public void testSave(){ String name = "a' or 1=1 or 1='"; String password ="123"; Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; conn = DBUtil.getCon(); String sql = "select * from users where username= ? and password=?"; try {pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, password); rs = pstmt.executeQuery(); if(rs.next()){ System.out.println(rs.getInt(1)); }else{ System.out.println("fuck"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
效率方面:
使用Statement:
@Test public void testEff(){ Connection conn =null; Statement stmt = null; conn = DBUtil.getCon(); long time = System.currentTimeMillis(); try{ stmt = conn.createStatement(); for(int i=0;i<5000;i++){ String sql = "insert into users (username,password) values ('1','123')"; stmt.executeUpdate(sql); } System.out.println(System.currentTimeMillis()-time); }catch(Exception e){ } } 输出为:122482 使用PreparedStatement: @Test public void testEff() { Connection conn = null; PreparedStatement pstmt = null; long time = System.currentTimeMillis(); conn = DBUtil.getCon(); conn = DBUtil.getCon(); String sql = "insert into users (username,password) values (?,?)"; try { pstmt = conn.prepareStatement(sql); for (int i = 0; i < 5000; i++) { pstmt.setString(1, "t"); pstmt.setString(2, "1233"); pstmt.executeUpdate(); } System.out.println(System.currentTimeMillis()-time); } catch (Exception e) { } } 输出为:135199 效率来说,PreparedStatement和Statement在mysql里,PreparedStatement不比Statement好。