此代码或许还有不正确的地方,不是最佳方案,但是能够满足事务的提交和回滚.
workshop中新建class文件(java),名字为jta.java,代码如下:
- package mypackage;
- import java.io.Serializable;
- import java.sql.*;
- import javax.sql.*;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.transaction.SystemException;
- import javax.transaction.UserTransaction;
- public class jta implements Serializable
- {
- public Context ctx;
- public UserTransaction tx;
- public DataSource ds;
- public Connection myConn;
- public Statement stmt;
- public String v_sqlstr;
- public void exeJTASQL()
- {
- int i;
- String l_sqlstr[];
- if ( v_sqlstr.trim().length() == 0 )
- {
- System.out.println("参数错误");
- }
- l_sqlstr = v_sqlstr.split(";");
- try
- {
- ctx = new InitialContext();
- tx = (UserTransaction)ctx.lookup("javax.transaction.UserTransaction");
- tx.begin();
- ds = (DataSource)ctx.lookup("CMSDS");
- myConn = ds.getConnection();
- stmt = myConn.createStatement();
- for ( i=0; i<l_sqlstr.length; i++ )
- {
- if ( l_sqlstr[i].startsWith("insert") == true ||
- l_sqlstr[i].startsWith("update") == true ||
- l_sqlstr[i].startsWith("delete") == true )
- {
- System.out.println(i + ":" + l_sqlstr[i]);
- stmt.executeUpdate(l_sqlstr[i].toString().toString());
- }
- }
- tx.commit();
- System.out.println("数据提交");
- stmt.close();
- System.out.println("关闭stmt");
- }
- catch ( Exception e)
- {
- System.out.println("执行出错 message:" + e);
- try
- {
- tx.rollback();
- System.out.println("事务回滚");
- }
- catch(SystemException se)
- {
- System.out.println("回滚错误 message:" + se);
- }
- }
- finally
- {
- try
- {
- if ( myConn != null )
- {
- if ( !myConn.isClosed() )
- {
- myConn.close();
- System.out.println("关闭myConn");
- }
- }
- }
- catch(SQLException sqle)
- {
- ;
- }
- }
- }
- public void setV_sqlstr(String v_sqlstr)
- {
- this.v_sqlstr = v_sqlstr;
- }
- }
在workshop中的jpf程序的Action中使用:
- import mypackage.jta;
- /**
- * @jpf:action
- * @jpf:forward name="success" path="newPage1.jsp"
- */
- protected Forward newAction1() throws Exception
- {
- String sqlstr;
- jta jtatest; /*创建类jta的一个实例jtatest*/
- jtatest = new jta(); /*初始化jtatest*/
- /*组装sqlstr语句,注意每个语句结束的";"符号,语句必须是insert,update,delete开头*/
- sqlstr = "insert into table values('aaaa',11,222,'aaaaaaa');";
- sqlstr = sqlstr + "update table1 set name='高级管理员';";
- sqlstr = sqlstr + "insert into table3 values('111',802,100);";
- System.out.println("sqlstr:" + sqlstr);
- jtatest.setV_sqlstr(sqlstr); /*将这段sql语句赋值给实例jtatest的成员变量*/
- jtatest.exeJTASQL(); /*调用方法*/
- return new Forward("success");
- }