D.png
{
DataSource dataSource = JdbcUtils.getDataSource();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sqlfa = "insert into tab_favorite values(?,?,?)";
String sqlroute = "update tab_route set count=count+1 where rid=?";
//生成日期对象
Date current_date = new Date();
//设置日期格式化样式为:yyyy-MM-dd
SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//格式化当前日期
String format = SimpleDateFormat.format(current_date.getTime());
Connection connection = null ;
try {
//注册一个事务同步管理器
TransactionSynchronizationManager.initSynchronization();
//从数据源中获取jdbcTemplate操作的当前连接对象
connection = DataSourceUtils.getConnection(dataSource);
//设置连接对象的事务提交方式为手动提交
connection.setAutoCommit(false);
jdbcTemplate.update(sqlfa, rid, format, uid);
//System.out.println("as = " + 1/0);
jdbcTemplate.update(sqlroute,rid);
//提交事务
connection.commit();
} catch (Exception e) {
//抛出异常说明事务失败 回滚事务
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
//清除事务并设置未自动提交事务
TransactionSynchronizationManager.clearSynchronization();
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
网友评论