包 my.view.jdbc; 导入 my.view.util.JdbcUtils02; 导入 java.lang.reflect.Method; 导入 java.sql.Connection; 导入 java.sql.PreparedStatement; 导入 java.sql.SQLException; public 类 JdbcDemo09 { public 静态 void main(字符串[] args){
连接连接 = null ;
PreparedStatement prepareStatement1 = null ;
PreparedStatement prepareStatement2 = null ; 试试 // 1.建立联系
connection = JdbcUtils02.getConnection();
// 未完成交易
connection.setAutoCommit(false );
// 2.定义sql
// 2.1定义SQL语句以减少帐户余额
字符串sql1 ="更新帐户集余额=余额-?其中id =?" ;
// 2.2 SQL语句定义帐户余额的增加
字符串sql2 ="更新帐户集余额=余额+?其中id =?" ;
// 3.获取执行SQL语句的对象
prepareStatement1 = connection.prepareStatement(sql1);
prepareStatement2 = connection.prepareStatement(sql2);
// 4.设置参数
// 4.1 LeeHua的帐户余额减少了500元
prepareStatement1.setDouble(1,500 );
prepareStatement1.setInt( 2,1 );
// 4.2 Tom的帐户余额增加了500元
prepareStatement2.setDouble(1,500 );
prepareStatement2.setInt( 2,2 );
// 5.执行SQL语句
prepareStatement1.executeUpdate();
prepareStatement2.executeUpdate();
// 6.提交事务
connection.commit();
} catch (异常e){
// 7.事务回滚
尝试 {
如果(连接!= null ){
connection.rollback();
}
} catch (SQLException e1){
e1.printStackTrace();
}
} 最终
// 8.释放资源
releaseResources(preparedStatement2);
releaseResources(preparedStatement1);
releaseResources(连接);
}
}
公共 静态 \ lt; T 无效 releaseResources(T t){
如果(t!= null ){
试试
// 使用反射获取类对象
类\\? \ Gt; aClass = t.getClass();
// 在类对象中获取方法对象
方法close = aClass.getMethod("关闭" );
// 实现方法
close.invoke(t);
} catch (异常e){
e.printStackTrace();
}
}
}
}