package jtasample;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.Properties;
import javax.transaction.*;
public class JTATest
{
public JTATest()
{
}
public static void main(String[] args)
{
DataSource ds = null;
Context ctx = null;
Connection myConn = null;
UserTransaction tx = null;
try
{
ctx = getInitialContext();
tx = (UserTransaction)
ctx.lookup("javax.transaction.UserTransaction");
tx.begin();
ds = (javax.sql.DataSource)
ctx.lookup ("mysqlDS");
}
catch (Exception E)
{
System.out.println("Init Error: " + E);
}
Statement myStatement = null;
ResultSet myResultSet = null;
try
{
myConn = ds.getConnection();
myStatement = myConn.createStatement();
myStatement.executeUpdate ("INSERT INTO emp (empname,empid,job) VALUES ('John', 10 ,'sales')");
tx.commit();
System.out.println("Success!");
}
catch (Exception e)
{
try
{
tx.rollback();
}
catch(Exception e1)
{
}
System.out.println("Error message = " + e.getMessage());
}
finally
{
try
{
if (myStatement != null)
{
myStatement.close();
}
if (myConn != null)
{
myConn.close();
}
}
catch (SQLException e)
{
System.out.println("Error code = " + e.getErrorCode());
System.out.println("Error message = " + e.getMessage());
}
}
}
private static Context getInitialContext() throws Exception
{
String url = "t3://localhost:7001";
String user = "weblogic";
String password = "zhangjane";
Properties properties = null;
try
{
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
if (user != null)
{
properties.put(Context.SECURITY_PRINCIPAL, user);
properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);
}
return new InitialContext(properties);
}
catch(Exception e)
{
throw e;
}
}
}
阅读(10408) | 评论(0) | 转发(0) |