是Statement的子接口,可以传入带占位符的sql语句,并且提供了补充占位符变量的方法。
使用Statement需要进行拼写SQL语句,很辛苦,很容易出错。
引号的问题处理很复杂,不利于维护。
可以有效的禁止sql注入。(通过用户输入非法的sql命令)
代码的可读性和可维护性,最大可能的提高性能(批量插入)
代码测试
public void testPreparedStatement() {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = JDBCTools.getConnection();
String sql = "insert into t_user (id, username, pwd, regTime, lastLoginTime) values(?,?,?,?,?)";
ps = connection.prepareStatement(sql);
ps.setInt(1, 2);
ps.setString(2, "狗贼");
ps.setString(3, "123456");
ps.setDate(4, new Date(System.currentTimeMillis()));
ps.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCTools.release(ps, connection);
}
}