慕尼黑5688855
a的优点PreparedStatement:预编译和sql语句的DB端缓存将导致总体上更快的执行和重用批次.自动预防SQL注入 攻击通过内置转义引号和其他特殊字符。请注意,这要求您使用任何PreparedStatement setXxx()方法来设置值。preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo) VALUES (?, ?, ?, ?)");
preparedStatement.setString(1, person.getName());preparedStatement.setString(2, person.getEmail());
preparedStatement.setTimestamp(3, new Timestamp(person.getBirthdate().getTime()));
preparedStatement.setBinaryStream(4, person.getPhoto());preparedStatement.executeUpdate();因此别通过字符串连接将SQL字符串中的值内联。preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email)
VALUES ('" + person.getName() + "', '" + person.getEmail() + "'");preparedStatement.executeUpdate();简化了SQL字符串中非标准Java对象的设置。Date, Time, Timestamp, BigDecimal, InputStream (Blob)和Reader (Clob)。在大多数这些类型中,您不能“只做”一个toString()就像你在一个简单的Statement..您甚至可以将其全部重构为PreparedStatement#setObject()在循环内部,如下面的实用程序方法所示:public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
preparedStatement.setObject(i + 1, values[i]);
}}如下所示:preparedStatement = connection.prepareStatement("INSERT INTO Person (name, email, birthdate, photo)
VALUES (?, ?, ?, ?)");setValues(preparedStatement, person.getName(), person.getEmail(),
new Timestamp(person.getBirthdate().getTime()), person.getPhoto());preparedStatement.executeUpdate();