Eclipse3.1.1+Webloigc 9.0通过数据源实现JDBC简单事务处理

1,接上篇 在Eclipse3.1.1访问Weblogic 9.0中数据源的JDBC简单应用关于数据源配置详见http://blog.csdn.net/blue_fire2008/archive/2008/05/08/2413398.aspx),在项目TestJDBC中新建类,名为:MyJTA,源代码如下:
package myjdbc;
 
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
 
public class MyJTA {
 
       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO 自动生成方法存根
              DataSource ds=null;
              Context ctx=null;
              Connection con=null;
              UserTransaction t=null;
              Statement st=null;
             
              Properties p=new Properties();
              p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
              p.put(Context.PROVIDER_URL,"t3://localhost:7001");
             
              try {
                     ctx=new InitialContext(p);
                     t=(UserTransaction)ctx.lookup("javax.transaction.UserTransaction");    //建立事务
                     t.begin(); //开始事务
                     ds=(DataSource)ctx.lookup("MySQLDS");
              } catch (Exception e) {
                     // TODO: handle exception
                     e.printStackTrace();
              }
              try {
                     con=ds.getConnection();
                     st=con.createStatement();
                     st.executeUpdate("insert into book values('1005','Benson','Master J2EE',59)");
                     t.commit();                   //提交事务
                     System.out.println("Inser Data,Success!");
              } catch (Exception e) {
                     // TODO: handle exception
                     try {
                            t.rollback();                  //事务回滚
                     } catch (Exception ex) {
                            // TODO: handle exception
                     }
                     e.printStackTrace();
              }finally{                //即使异常也能关闭语句对象及连接
                     try {
                            if (st!=null) {
                                   st.close();
                            }
                            if (con!=null) {
                                   con.close();
                            }
                     } catch (SQLException e) {
                            // TODO: handle exception
                            e.printStackTrace();
                     }
              }
       }
 
}
2,启动MySQL和Weblogic服务器,运行MyJTA,若控制台显示: Inser Data,Success!,表示成功插入数据.
3,可在MySQL控制台用select命令查看数据.(注:这里没有就中文插入乱码问题进行处理).
欢迎转载,转载请注明出处!
(
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页