PreparedStatement的使用----JDBC-2

来源:互联网 发布:植发失败 知乎 编辑:程序博客网 时间:2024/06/05 02:52

今天可是双十二,各种超市五折,各种支付宝结算五折,而苦逼的我还在这里写博客。。。

谁让我是一只程序员,重点是还单身难过

言归正传,今天说的是PreparedStatement,它是Statement的子接口,其作用也和Statement一样,但是有不少优点:

总结:PreparedStatement VS Statement

1.简化程序

2.防止SQL注入

3.提高性能


大家刚学JDBC的时候是不是老是在拼写sql语句时出现错误,而且不易发现,搞得大家很头疼。

今天这个PreparedStatement就可以大大减轻我们的工作量还不容易出错,具体请看代码!


              /**       *@author HelloWorld 2015/12/12       *       */        @Testpublic 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();} }}}


如有不足之处请多多指教奋斗如果觉得对你有帮助请点赞支持害羞


1 0