jtademo.java

来自「事务表示一个由一系列的数据库操作组成的不可分割的逻辑单位」· Java 代码 · 共 58 行

JAVA
58
字号
package ch4;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;
public class JTADemo {

	public static void main(String[] args) {
		
		Properties p=new Properties();
		Context ctx=null;
		UserTransaction tx=null;
		String sqlstr1,sqlstr2;
		Connection con=null;
		Statement stmt=null;
		try{
			p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
			p.put(Context.PROVIDER_URL,"t3://localhost:7001");
			ctx=new InitialContext(p);
			tx=(UserTransaction)ctx.lookup("javax.transaction.UserTransaction");
			sqlstr1="insert into studentinfo(id,name,dept) VALUES('1005','tom','art')";
		//sqlstr2="insert into studentinfo(id,name,dept) VALUES('1005','white','computer')";
			sqlstr2="insert into studentinfo(id,name,dept) VALUES('1006','white','computer')";
			tx.begin();
			DataSource ds=(DataSource)ctx.lookup("MysqlDatasource");
			con=ds.getConnection();
			stmt=con.createStatement();
			stmt.executeUpdate(sqlstr1);
			stmt.executeUpdate(sqlstr2);
			tx.commit();
			System.out.println("事务被成功提交!");
		}
		catch(Exception ex){
			try{
				tx.rollback();
			}catch(Exception e){
				
			}
			ex.printStackTrace();
			System.out.println("事务发生错误!事务被取消!");
		}
		finally{
			try{
				if(con!=null) con.close();
			}
			catch(SQLException e){
				e.printStackTrace();
			}
		}
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?