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();
}
}
}
}
控制数据的安全访问;
直接上代码:
》》》》》》》》》》》》》》》》》》》》》》》》》》》》》
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();
}
}
}
}
相关文章推荐
- poj1321题解(也是我的第一篇博客)
- 拒绝传统,看 Facebook 如何以三大法宝化茧成蝶:人才吸引、工程师文化和项目开发流程
- OC 创建和写入plist文件
- freemark常见用法
- VC线程安全退出的方法
- struts2 s:select使用
- 适配器、工厂模式、线程池、线程组、互斥锁、Timer类、Runtime类、单例设计模式(二十四)
- POJ 1915 Knight Moves
- UDP程序设计
- 增强学习(Q-learning)
- 内存问题--全局变量被修改
- sql笔记
- Core Animation
- 21分钟mysql入门教程
- JS实现表单的验证
- map几种方法
- 公众号判断用户是否已关注php代码
- OC 对象和匿名对象
- OpenWRT with OpenvSwitch 刷路由器教程
- Mysql迁移到Oracle简单记录