优化以下代码 :SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String format = sdf.format(new Date()); format += " 00:00:01"; System.out.println(format); Connection connection = null; PreparedStatement pstm = null; ResultSet rs = null; OracleConnection1 oracleConnection1 = new OracleConnection1(); OracleConnection2 oracleConnection2 = new OracleConnection2(); connection = oracleConnection2.getConnection(); String SQLstr = "SELECT COUNT(1) FROM jy_xx_pkjf xx WHERE xx.jqrq >= to_date('"+format+"','yyyy-mm-dd hh24:mi:ss')"; int sum = 0; try { pstm = connection.prepareStatement(SQLstr); rs = pstm.executeQuery(SQLstr); if (rs.next()) { sum = rs.getInt(1); } } catch (SQLException throwables) { throwables.printStackTrace(); System.exit(0); } finally { oracleConnection2.ReleaseResource(); } String SQLstr2 = "INSERT INTO testi" + "nfo(frrq,gsdm,gsmc,zbs) values (sysdate,?,?,?)"; System.out.println(SQLstr2); connection = oracleConnection1.getConnection(); try { pstm = connection.prepareStatement(SQLstr2); pstm.setInt(1,123); pstm.setString(2,"神码"); pstm.setInt(3,sum); System.out.println(pstm); pstm.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { oracleConnection2.ReleaseResource(); }
时间: 2023-06-05 16:08:49 浏览: 165
深入理解Java:SimpleDateFormat安全的时间格式化
5星 · 资源好评率100%
优化代码如下:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatDate = sdf.format(new Date());
String SQLstr = "SELECT COUNT(1) FROM jy_xx_pkjf xx WHERE xx.jqrq >= to_date('" + formatDate + "','yyyy-mm-dd hh24:mi:ss')";
System.out.println(SQLstr);
try (Connection connection = oracleConnection2.getConnection();
PreparedStatement pstm = connection.prepareStatement(SQLstr);
ResultSet rs = pstm.executeQuery(SQLstr)){
if (rs.next()) {
int sum = rs.getInt(1);
String SQLstr2 = "INSERT INTO testinfo(frrq,gsdm,gsmc,zbs) values (sysdate,?,?,?)";
System.out.println(SQLstr2);
try (PreparedStatement pstm2 = connection.prepareStatement(SQLstr2)) {
pstm2.setInt(1, 123);
pstm2.setString(2, "神码");
pstm2.setInt(3, sum);
System.out.println(pstm2);
pstm2.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
oracleConnection2.ReleaseResource();
}
优化的主要思路是:
1.将日期格式化的代码放在SQL语句字符串拼接时完成,不需要新建变量保存。
2.使用try-with-resources结构,简化代码结构,避免忘记关闭资源。
3.将数据库连接、执行SQL语句的代码放在同一个try块里面,减少出错的可能性。
4.将SQL语句2的执行代码放在SQL语句1的if块里面,当查询结果不为空时才进行插入操作,避免不必要的执行。
阅读全文