JDBC学习笔记--PreparedStatement
1.Why:
①使用Statement需要进行拼写SQL语句,容易出错,不利于维护
String sql = "INSERT INTO examstudent" + " VALUES("
+ student.getFlowid() + ", "
+ student.getType() + ", '"
+ student.getIdCard() + "', '"
+ student.getExamCard() + "', '"
+ student.getStudentName() + "', '"
+ student.getLocation() + "', "
+ student.getGrade() + ")";
②可以有效的禁止SQL注入.
SELECT *FROM users WHERE username = 'a' OR PASSWORD = ' AND password = ' OR '1'='1';//这条语句会把表中所有数据都查询出来
String username = "a' OR PASSWORD = ";//这样操作也可以登录成功!
String password = " OR '1'='1";
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
SQL注入:利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,从而利用系统的SQL引擎完成恶意行为的做法;
对于Java而言,要防范SQL注入,只要用PreparedStatement取代Statement就可以了.
③PreparedStatement能最大可能提高性能
2.What:
1).是Statement的子接口;
2).可以传入带占位符SQL语句;
3).并且提供了补充占位符变量的方法。
3.How:
①创建PreparedStatement:
String sql = "INSERT INTO examstudent VALUES(?, ?, ?, ?, ?, ?, ?)"
PreparedStatement ps = conn.prepareStatement(sql);
②调用PreparedStatement的setXxx(int index, Object val)设置占位符的值
index从1开始
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
③执行SQL语句:executeQuery() 或 executeUpdate().注意:执行时不再需要传入SQL语句