我们之前用的Statement对象向数据库发送要执行的语句,但是Statement有很多的不足:
1.大量的字符串拼接,代码可读性降低。
2.sql注入:
SQL注入有一个BUG:
就是通过字符串的拼接,可以得到一个恒等的sql语句,可以跳过某些判断:
( "b' or '1' = '1" )--------这个语句返回值一定是true,所以可以通过任何的验证
例如:
这样无论用户名是什么都可以登陆成功。
public static void main(String[] args) {
login("zxcvzxcvzxcv","b' or '1' = '1");
}
public static void login(String username,String password) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
stmt = conn.createStatement();
String sql = "select * from user where username = '"
+ username + "' and password = '" + password + "'";
System.out.println("sql:" + sql);
rs = stmt.executeQuery(sql);
if(rs.next()){
System.out.println("登录成功,欢迎回来:" + username);
}else {
System.out.println("账号或密码错误!");
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.close(conn,stmt,rs);
}
}
PreparedStatement(预编译(预加载)接口)
预编译语句PreparedStatement 是java.sql中的一个接口,它是Statement的子接口。通过Statement对象执行SQL语句时,需要将SQL语句发送给DBMS,由DBMS首先进行编译后再执行。预编译语句和Statement不同,在创建PreparedStatement 对象时就指定了SQL语句,该语句立即发送给DBMS进行编译。当该编译语句被执行时,DBMS直接运行编译后的SQL语句,而不需要像其他SQL语句那样首先将其编译。
使用:
1.通过connection获取的对象
2.是Statement接口的子接口
3.sql语句中可以传参。用?占位,通过setXXX方法来给?赋值
eg:setString(索引,值);
4.提高性能
5.避免sql注入
例子:
public void test03() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
String sql = "select * from user where username = ? and password = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,"aaa");
pstmt.setString(2,"b' or '1' = '1");
rs = pstmt.executeQuery();
if(rs.next()) {
System.out.println("登录成功...");
}else {
System.out.println("账号或密码错误...");
}
}catch (SQLException e) {
throw new RuntimeException(e);
}finally {
JDBCUtil.close(conn,pstmt,rs);
}
}