您的位置:首页 > 其它

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

2016-05-12 10:06 267 查看
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();

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: