#題目 1(100分) 有一張學生表sql
如今須要根據學生名稱獲取學生的期末考試分數。數據庫
public static void getStudent(String name) throws ClassNotFoundException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); rs = stmt.executeQuery("select name,score from student where name =' " + name +"'"); while (rs.next()) { System.out.println(rs.getString("name") + ":" + rs.getInt("score")); } } catch (SQLException e) { // ignore } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { // ignore } } if (stmt != null) { try { stmt.close(); } catch (Exception e) { // ignore } } if (conn != null) { try { conn.close(); } catch (SQLException e) { // ignore } } } }
##初始化SQL安全
CREATE TABLE `student` ( `Id` int NOT NULL AUTO_INCREMENT , `name` varchar(100) NULL , `score` int NULL , PRIMARY KEY (`Id`) ) ; INSERT INTO `student` (`Id`, `name`, `score`) VALUES ('1', 'Xiaoming', '100'); INSERT INTO `student` (`Id`, `name`, `score`) VALUES ('2', 'XiaoLi', '101'); INSERT INTO `student` (`Id`, `name`, `score`) VALUES ('3', 'XiaoZhao', '102');
##解答測試
public void testGetStudentBug() throws Exception { StudentDAO.getStudent("XiaoMing\' OR 1=1; -- "); }
運行結果code
[SQL]:select name,score from student where name ='XiaoMing' OR 1=1; -- ' Xiaoming:100 XiaoLi:101 XiaoZhao:102
2.如下是從新編寫的代碼,進行風險規避get
public static void getStudentSafe(String name) throws ClassNotFoundException { Connection conn = null; PreparedStatement preparedStatement = null; ResultSet rs = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "SELECT name,score FROM student WHERE name = ?"; System.out.println("SQL:" + sql); preparedStatement = conn.prepareStatement(sql); preparedStatement.setString(1,name); rs = preparedStatement.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name") + ":" + rs.getInt("score")); } } catch (SQLException e) { // ignore System.out.println("[SQLException]:" + e.toString()); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { // ignore } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { // ignore } } if (conn != null) { try { conn.close(); } catch (SQLException e) { // ignore } } } }
測試代碼it
public void testGetStudentSafe1() throws Exception { StudentDAO.getStudentSafe("XiaoMing"); } public void testGetStudentSafe() throws Exception { StudentDAO.getStudentSafe("XiaoMing\' OR 1=1; -- "); }
錯誤的執行結果io
SQL:SELECT name,score FROM student WHERE name = ? Process finished with exit code 0