时间:2021-07-01 10:21:17 帮助过:10人阅读
3、PreparedStatement 可以防止 SQL 注入。
例子:
@Test public void testPreparedStatement() { Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCTools.getConnection(); String sql = "INSERT INTO customers (name, email, birth) " + "VALUES(?,?,?)"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "soyoungboy"); preparedStatement.setString(2, "soyoungboy@163.com"); preparedStatement.setDate(3, new Date(new java.util.Date().getTime())); preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.releaseDB(null, preparedStatement, connection); } }
概念:
SQL 注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的 SQL 语句段或命令,从而利用系统的 SQL 引擎完成恶意行为的做法。
对于 Java 而言,要防范 SQL 注入,只要用 PreparedStatement 取代 Statement 就可以了。
sql注入例子:
/** * SQL 注入. */ @Test public void testSQLInjection() { String username = "a‘ OR PASSWORD = "; String password = " OR ‘1‘=‘1"; String sql = "SELECT * FROM users WHERE username = ‘" + username + "‘ AND " + "password = ‘" + password + "‘"; System.out.println(sql); Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = JDBCTools.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(sql); if (resultSet.next()) { System.out.println("登录成功!"); } else { System.out.println("用户名和密码不匹配或用户名不存在. "); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.releaseDB(resultSet, statement, connection); } }
使用PreparedStatement 解决sql注入例子:
/** * 使用 PreparedStatement 将有效的解决 SQL 注入问题. */ @Test public void testSQLInjection2() { String username = "a‘ OR PASSWORD = "; String password = " OR ‘1‘=‘1"; String sql = "SELECT * FROM users WHERE username = ? " + "AND password = ?"; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = JDBCTools.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, username); preparedStatement.setString(2, password); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { System.out.println("登录成功!"); } else { System.out.println("用户名和密码不匹配或用户名不存在. "); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.releaseDB(resultSet, preparedStatement, connection); } }
Java -- JDBC 学习--PreparedStatement
标签:最大 输入 select into too sts injection 相同 语句