某个线程处理回调时,需要对数据库进行操作,本来可以这样:
我觉得自已的项目用sping,而且不想对释放资源进行管理,所以就改成这样:
简单几行就可以了。
public int update(int id) {
Connection conn = null;
PreparedStatement stmt = null;
int rows = -1;
try{
conn = getConnection();
String sql = "update xxlog set result=1 where id=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rows = stmt.executeUpdate();
} catch (Exception se) {
logger.error("update,error!", se);
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null && !conn.isClosed()) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return rows;
}
public static Connection getConnection() {
Connection conn = null;
try {
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) ctx.lookup("jdbc/xxxxx");
conn = ds.getConnection();
} catch (Throwable se) {
logger.error("getConnection ERROR!" + se);
}
return conn;
}
我觉得自已的项目用sping,而且不想对释放资源进行管理,所以就改成这样:
WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
SimpleJdbcTemplate simpleJdbcTemplate = (SimpleJdbcTemplate) context.getBean("simpleJdbcTemplate");
String sql="update xxlog set result=1 where id=?";
int result = simpleJdbcTemplate.update(sql, orderId);
简单几行就可以了。