今天可是双十二,各种超市五折,各种支付宝结算五折,而苦逼的我还在这里写博客。。。
谁让我是一只程序员,重点是还单身
言归正传,今天说的是PreparedStatement,它是Statement的子接口,其作用也和Statement一样,但是有不少优点:
总结:PreparedStatement VS Statement
1.简化程序
2.防止SQL注入
3.提高性能
大家刚学JDBC的时候是不是老是在拼写sql语句时出现错误,而且不易发现,搞得大家很头疼。
今天这个PreparedStatement就可以大大减轻我们的工作量还不容易出错,具体请看代码!
/**
*@author HelloWorld 2015/12/12
*
*/
@Test
public void testPreparedStatement() {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
//获取数据库链接,具体方法可以查看往期博文
connection = getConnection();
//向oracle数据库中的customer表插入数据
String sql ="insert into customer (id,name ,email ,birth)" +
"values(customer_seq.nextval,?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "charles");
preparedStatement.setString(2, "479846@fejifje");
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
preparedStatement.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
} finally {
//关闭相应的资源
if(preparedStatement != null) {
try {
preparedStatement.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}