本人微信公衆號,歡迎掃碼關注!sql
@Test public void statementTest() { String username = "tom"; String sex = "1"; String address = "' or '1'='1"; Statement stat = null; ResultSet res = null; Connection conn = ConnectionFactory.getConnection(); String sql = "SELECT * FROM user WHERE 1 = 1"; sql += username == null ? "" : " AND username = '" + username + "'"; sql += sex == null ? "" : " AND sex = '" + sex + "'"; sql += address == null ? "" : " AND address = '" + address + "'"; System.out.println(sql); try { stat = conn.createStatement(); res = stat.executeQuery(sql); printRes(res); } catch (SQLException e) { e.printStackTrace(); } finally { ResourceClose.close(res, stat, conn); } }
SELECT * FROM user WHERE 1 = 1 AND username = 'tom' AND sex = '1' AND address = '' or '1'='1' 10 tom 2014-07-10 1 beijing 16 tom 2018-07-31 1 shanghai 22 tom 2019-04-16 2 shanghai 24 tom 2019-06-22 1 guangzhou 25 tom 2019-01-22 2 guangzhou 28 tom 2018-07-31 1 shenzhen
@Test public void prepareStatementTest() { String username = "tom"; String sex = null; String address = "' or '1'='1"; PreparedStatement stat = null; ResultSet res = null; Connection conn = ConnectionFactory.getConnection(); String sql = "SELECT * FROM user WHERE 1 = 1"; List<Object> param = new ArrayList<>(); if (username != null) { sql += " AND username = ?"; param.add(username); } if (sex != null) { sql += " AND sex = ?"; param.add(sex); } if (address != null) { sql += " AND address = ?"; param.add(address); } System.out.println(sql); try { stat = conn.prepareStatement(sql); for (int i = 0; i < param.size(); i++) { stat.setObject(i+1,param.get(i)); } res = stat.executeQuery(); printRes(res); } catch (SQLException e) { e.printStackTrace(); } finally { ResourceClose.close(res, stat, conn); } }
SELECT * FROM user WHERE 1 = 1 AND username = ? AND address = ?