⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jtademo.java

📁 事务表示一个由一系列的数据库操作组成的不可分割的逻辑单位
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -