jdbc--的事务深入和存储过程的调用

1. 事务 的用处就是 : 保证多个 操作步骤能够成功

   控制数据的安全访问;

     直接上代码:

》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

public class Test1 {


public static void main(String[] args) {
//jdbc操作事务

String url="jdbc:sqlserver://localhost:1433;DataBaseName=XT003";
String user="sa";
String password="123456";


try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection sqlcon =null;

PreparedStatement pst=null;

try{
sqlcon = DriverManager.getConnection(url, user, password);


String sql1="insert into userinfo values('zhangsan','zhangsan')";
String sql2="insert into userinfo values('lisi','lisi')";
String sql3="insert into userinfo values('wangwu','wangwu')";


sqlcon.setAutoCommit(false);先把自动提交取消

pst=sqlcon.prepareStatement(sql1);
pst.execute(); 每一步都需要 判断
System.out.println("第一条语句执行。。。");

pst=sqlcon.prepareStatement(sql2);
pst.execute();
System.out.println("第二条语句执行。。。");

pst=sqlcon.prepareStatement(sql3);
pst.execute();
System.out.println("第三条语句执行。。。");

sqlcon.commit();如果没有错误 就会提交

}catch(SQLException e){
e.printStackTrace();
try {
sqlcon.rollback();有错就会回滚
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
try{
if(pst!=null){
pst.close();
}
if(sqlcon!=null){
sqlcon.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}


}


}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值