try-with-resource语法糖优化

本文展示了如何使用Java的try-with-resources语法糖优化资源关闭操作,避免手动在finally块中关闭连接和预编译语句,提高代码的可读性和安全性。示例代码比较了优化前后的saveMessage方法,强调了try语句块后括号内声明的AutoCloseable资源会在执行完毕后自动调用close方法。
摘要由CSDN通过智能技术生成

//实际方法
//现在是一个嵌套try,并且还是未进行优化的关流
public void saveMessage(String keycde,String xmlStr,String type,String fromStr) throws PublicException{
Connection conn = null;
PreparedStatement state = null;
try {
try {
conn = this.commonDao.getNewConnection();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new PublicException(“保存报文失败:获取不到连接”,e);
}
String sql = “insert into web_interface_msg” +
“(C_ID,C_KEY_CDE,C_MSG,C_REQUEST_TYPE,C_FROM,C_CRT_CDE,T_CRT_TM,C_UPD_CDE,T_UPD_TM)”
+ " values"
+ “(replace(uuid(), ‘-’, ‘’),?,?,?,?,?,now(),?,now())”;
state = conn.prepareStatement(sql);
state.setString(1, keycde);
state.setCharacterStream(2, new StringReader(xmlStr), xmlStr.length());
state.setString(3, type);
state.setString(4, fromStr);
state.setString(5, “posService”);
st

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值