你要先去oracle的网站down一个jdbc的驱动。
然后用jdbc联接。
然后用jdbc联接。
解决方案 »
- 菜鸟高分求教如何在JSP文件中写个函数返回值
- 谁帮我看看这段代码老报异常java.util.ConcurrentModificationException
- 求jsp页面js写的日期控件
- 将姓名编译成字母全拼的jar包,测试一切没问题!
- 做群集时,Hibernate 产生主键的问题?
- 高分请教 ping 地址的问题!
- 请教各位:如何用calendar获得两位数的月份和日期?
- servlet中的内容怎么才能在jsp页面上显示(急,再现等候,谢!!)
- 请教一个hibernate 误操作后的问题??
- 如何配置localhost的二级域名?例如http://test.localhost
- jsp的error 500是什么错误?
- NT+Apache+Jserv+tomcat对于servlet的路径怎么设定
1.java (basic skill)
2.servlet (implement an interface)
3.jdbc (just a api set of Java db access)
4.oracle jdbc (jdbc driver for oracle database)so, what's your main question?U know, i'm a lazy guy. SO, i found an example from technet.oracle.com. I wish it will be helpful but not too complex to u. Happy new year.http://technet.oracle.com/sample_code/tech/java/sqlj_jdbc/files/jdbc20/DistributedTransaction/DistributedTransactionServlet.java============================================================
/**
* @author Stephen Raj
* @version 1.0
*
* Development Environment : JDeveloper 3.0
* Name of the Application : DistributedTransaction.java
* Creation/Modification History :
*
* sarokias.in 20-Jan-2000 Created
*
* Overview of Application :
*
* Support for distributed transactions demands a JDBC driver to support the
* standard two-phase commit protocol used by the Java Transaction API (JTA).
*
* To demonstrate Distributed Transactions Support, the Sample uses following
* scenario.
*
* In this Sample, we assume that apart from 'TRAVEL' user, there exists another
* user namely 'GLOBAL'. This user may exist in the same database instance or
* some other database instance.
* We assume that there exists a table called 'EXCHANGE_RATES' in
* 'GLOBAL' user. The table 'EXCHANGE_RATES' keeps track of currency exchange
* rates between two countries. This table is similar to EXCHANGE_RATES table
* in 'TRAVEL' user.
*
* This servlet allows the user to update exchange rates between two different
* countries. As the table 慐XCHANGE_RATES" exists in two different users in
* two different database instances, the updation of exchange rates forms a
* distributed transaction. In short, this means, either the new rates should
* get reflected in both the tables or not at all. (ACID Properties)
*
**/package DistributedTransaction; // Package Name// Package for Servlet
import javax.servlet.*;
import javax.servlet.http.*;import java.io.*; // Package for I/O
import java.util.*; // Package for Vectors// Package for JDBC related Classes
import java.sql.*;
import javax.sql.*;
//import oracle.jdbc.driver.*;
//import oracle.jdbc.pool.*;
import oracle.jdbc.xa.OracleXid;
//import oracle.jdbc.xa.OracleXAException;
import oracle.jdbc.xa.client.*;
import javax.transaction.xa.*;public class DistributedTransactionServlet extends HttpServlet { // Distributed Transaction Connection Pool Objects
XAConnection m_xaConnectionTravel;
XAConnection m_xaConnectionGlobal; String m_servletPath = null; // Servlet Path
String m_rate = null; // Exchange Rate
Vector m_tableVector = null; // Vector for getting the values from table /**
* This method is called when the servlet is called for the first time. This
* method acts as the initializer for this servlet. Database connection object
* is initialized and populates the table with country details.
**/
public void init(ServletConfig config) throws ServletException { super.init(config); // Call Super Class init() method
this.createConnection(); // Establish database connection
m_tableVector = this.populateTable(); // Populate the table
} /**
* This method is called whenever a servlet is called .In this method we check
* for the value of parameter 'REQ_TYPE' and depending on it's value, call
* different functions which return HTML page in form of a String and display it.
**/
public void service(HttpServletRequest p_req, HttpServletResponse p_res)
throws ServletException, IOException { p_res.setHeader("pragma","no-cache"); // Disable cashe
p_res.setContentType("text/html"); // Set content type to HTML // Get the output stream
PrintWriter l_out = new PrintWriter (p_res.getOutputStream()); // get the value of REQ_TYPE
String l_reqType = p_req.getParameter("REQ_TYPE"); // If REQ_TYPE is null display the main page
if(l_reqType == null ){
m_servletPath = p_req.getServletPath();
l_out.println(DistributedTransactionHTML.generateMainPageHTML(m_servletPath));
} // If REQ_TYPE is HOME, show the countries as Home countries from the
// exchange_rates table present in the the user TRAVEL
else if(l_reqType.equals("HOME")) {
l_out.println(DistributedTransactionHTML.generateTableFrameHTML(
m_tableVector,m_servletPath,"Home Country" ));
} // If REQ_TYPE is DESTINATION, show the countries as destination countries
// from the exchange_rates table present in the the user TRAVEL
else if(l_reqType.equals("DESTINATION")) {
l_out.println(DistributedTransactionHTML.generateTableFrameHTML(
m_tableVector,m_servletPath,"Destination Country" ));
} // If REQ_TYPE is BUTTON display the various buttons
else if(l_reqType.equals("BUTTON"))
l_out.println(DistributedTransactionHTML.generateButtonFrameHTML(m_servletPath)); // If REQ_TYPE is INPUT display the text box to show and get Exchange rate
else if(l_reqType.equals("INPUT"))
l_out.println(DistributedTransactionHTML.generateInputFrameHTML("")); // If REQ_TYPE is UPDATE update the Exchange rates
else if(l_reqType.equals("UPDATE")) { // Get Home country ID
int l_hotelID = Integer.parseInt(p_req.getParameter("HOME_ID")); // Get Destination Country ID
int l_destinationID = Integer.parseInt(p_req.getParameter("DESTINATION_ID")); // Get Exchange rate
float l_value = Float.parseFloat(p_req.getParameter("VALUE")); this.updateTables(l_hotelID,l_destinationID,l_value); // Call update method
this.getExchangeRate(l_hotelID,l_destinationID); // Get Exchange rates // Display new Exchange rate
l_out.println(DistributedTransactionHTML.generateInputFrameHTML(m_rate));
} // If REQ_TPYE is INPUTUPDATE, display the Exchange rate
else if(l_reqType.equals("INPUTUPDATE")) { // Get Home country ID
int l_hotelID = Integer.parseInt(p_req.getParameter("HOME_ID")); // Get Destination Country ID
int l_destinationID = Integer.parseInt(p_req.getParameter("DESTINATION_ID")); this.getExchangeRate(l_hotelID,l_destinationID); // Get Exchange rates // Display new Exchange rate
l_out.println(DistributedTransactionHTML.generateInputFrameHTML(m_rate));
}
l_out.close(); // Close the output stream
} /**
* Creates database connection pool objects that can participate in
* Distributed Transaction using JDBC 2.0.
**/
public void createConnection() {
try {
// Create a OracleConnectionPoolDataSource instance
OracleXADataSource l_oxadsTravel = new OracleXADataSource();
OracleXADataSource l_oxadsGlobal = new OracleXADataSource(); // Set connection parameters
String l_urlTravel = "jdbc:oracle:thin:@"+ConnectionParams.s_hostName+":"
+ConnectionParams.s_portNumber+":"+ConnectionParams.s_databaseSID; // Set connection parameters
String l_urlGlobal = "jdbc:oracle:thin:@"+ConnectionParams2.s_hostName+":"
+ConnectionParams2.s_portNumber+":"+ConnectionParams2.s_databaseSID; // Set the URL
l_oxadsTravel.setURL(l_urlTravel);
l_oxadsGlobal.setURL(l_urlGlobal);
// Create the connection pools
m_xaConnectionTravel = l_oxadsTravel.getXAConnection(
ConnectionParams.s_userName,ConnectionParams.s_password);
m_xaConnectionGlobal = l_oxadsGlobal.getXAConnection(
ConnectionParams2.s_userName,ConnectionParams2.s_password); if (m_xaConnectionTravel == null || m_xaConnectionGlobal == null)
System.out.println("Error in creating Connection Pool"); } catch(SQLException ex){ // Trap SQL errors
System.out.println("Error in Connecting to the Database "+'\n'+ex.toString());
}
} /**
* This function returns a Transaction ID for the Transaction. The transaction
* ID contains 2 parts, a global Transaction ID which is set to 9 in this
* method and a Branch ID that is unique to each branch which is set to the
* value passed as parameter.
**/
public static Xid createXid(int p_bID) throws XAException {
byte[] l_gID = new byte[1]; // Global ID
l_gID[0] = (byte) 9; // Set Global Id to 9
byte[] l_bID = new byte[1]; // Branch ID
l_bID[0] = (byte) p_bID; // Set branch ID to the parameter passed byte[] l_globalID = new byte[64];
byte[] l_branchID = new byte[64]; // Copy the Global ID and branch ID to a 64 bit string
System.arraycopy (l_gID, 0, l_globalID, 0, 1);
System.arraycopy (l_bID, 0, l_branchID, 0, 1); // Call OracleXid() to generate the Xid
Xid l_xid = new OracleXid(0x1234, l_globalID, l_branchID); // Return the Transaction ID
return l_xid;
} /**
* This method retrieves all rows from the HOTELS table and populates the
* Vector with all the hotel details. This Vector will be used to display
* main HTML page
**/
public Vector populateTable(){
Vector l_hotelDetails = new Vector(); // Get new vector
Connection l_connection = null; // Connection used
try{
// Get a connection from the pooled Transaction connection object
l_connection = m_xaConnectionTravel.getConnection(); // Statement Context to execute SQL query
Statement l_statement = l_connection.createStatement(); // Retrieve all rows from the hotels table into a ResultSet with country ID
// less than 10. Countries with ID greater than 10 do not have exchange
// rates value in the database.
ResultSet l_resultSet=l_statement.executeQuery(
"select id,name,currency from countries where id <= 10"); // Loop through the result-set, obtain column values and add to Vector
while (l_resultSet.next()){
Vector l_hotel = new Vector();
l_hotel.addElement( l_resultSet.getString(1)); // Hotel ID
l_hotel.addElement( l_resultSet.getString(2)); // Hotel Name
l_hotel.addElement( l_resultSet.getString(3)); // Hotel Address
l_hotelDetails.addElement(l_hotel); // Add to vector
} l_statement.close(); // Close the statement } catch(SQLException ex) { // Trap SQL Errors
System.out.println("Error in retrieving data from database "+ex.toString());
} finally { // return the connection object to the pool
if (l_connection != null) {
try {
l_connection.close();
} catch(SQLException e) { // Trap SQL Errors
System.out.println("Error..."+e.toString());
}
}
}
return l_hotelDetails; // Return the Vector
} /**
* This methods returns the Exchange rate. This method gets the home country ID
* destination country ID and queries the exchange_rates table in the TRAVEL
* user to return the exchange rate.
**/
private void getExchangeRate(int p_homeID,int p_destinationID) {
Connection l_connection = null; // connection Object
try {
l_connection = m_xaConnectionTravel.getConnection(); // Get connection // Prepare statement for query
Statement l_stmt = l_connection.createStatement(); // Execute Query
ResultSet l_rs = l_stmt.executeQuery("select rate from exchange_rates "+
"where home_con_id="+p_homeID+" and new_con_id=" + p_destinationID); if(l_rs.next())
m_rate= l_rs.getString(1); // Get Exchange rate from Result Set } catch(SQLException ex){ // Trap SQL Errors
System.out.println("Error in Getting Rate "+ex.toString());
} finally { // return the connection object to the pool
if (l_connection != null)
try {
l_connection.close();
} catch(SQLException e) { // Trap SQL Errors
System.out.println("Error...."+e.toString());
}
}
} /**
* This method updates the exchange_rates table in TRAVEL user and in GLOBAL
* user. If any one of the tables fails to get updated, then the database roll
* backs to the previous state.
**/
private void updateTables(int p_homeID,int p_destinationID,float p_exchangeRate) {
Connection l_connectionTravel = null; // Connection to TRAVEL user
Connection l_connectionGlobal = null; // Connection to GLOBAL user
try {
// Get the database connection from Connection Pool
l_connectionTravel = m_xaConnectionTravel.getConnection();
l_connectionGlobal = m_xaConnectionGlobal.getConnection(); // Get the Transaction Resources
XAResource l_xaResourceTravel = m_xaConnectionTravel.getXAResource();
XAResource l_xaResourceGlobal = m_xaConnectionGlobal.getXAResource(); // Create the Transaction IDs
Xid l_xidTravel = createXid(1);
Xid l_xidGlobal = createXid(2); // Start transaction
l_xaResourceTravel.start (l_xidTravel, XAResource.TMNOFLAGS);
l_xaResourceGlobal.start (l_xidGlobal, XAResource.TMNOFLAGS); // Create Statements for updating
Statement l_stmtTravel = l_connectionTravel.createStatement();
Statement l_stmtGlobal = l_connectionGlobal.createStatement(); // Execute the Update Statements
int l_no = l_stmtTravel.executeUpdate("update exchange_rates set rate="+p_exchangeRate+
" where home_con_id="+p_homeID+" and new_con_id=" + p_destinationID); l_no = l_stmtGlobal.executeUpdate("update exchange_rates set rate="+
p_exchangeRate+" where home_con_id="+p_homeID+" and new_con_id="
+ p_destinationID); // Suspend the transactions
l_xaResourceTravel.end(l_xidTravel, XAResource.TMSUCCESS);
l_xaResourceGlobal.end(l_xidGlobal, XAResource.TMSUCCESS); // Prepare the Resource Managers
int l_prepareGlobal = l_xaResourceGlobal.prepare (l_xidGlobal);
int l_prepareTravel = l_xaResourceTravel.prepare (l_xidTravel); boolean l_doCommit = true; // Boolean to check whether to commit or not // If both the branches are to the same Resource Manager, oracle does some
// optimization. All but one branch return XA_RDONLY. Only one branch will
// return XA_OK or failure. Commit or Rollback has to be called on this
// branch only accordingly. if (!((l_prepareTravel == XAResource.XA_OK)||(l_prepareTravel==XAResource.XA_RDONLY)))
l_doCommit = false; if (!((l_prepareGlobal == XAResource.XA_OK)||(l_prepareGlobal==XAResource.XA_RDONLY)))
l_doCommit = false; if (l_prepareTravel == XAResource.XA_OK)
if (l_doCommit)
l_xaResourceTravel.commit(l_xidTravel, false);
else
l_xaResourceTravel.rollback(l_xidTravel); if (l_prepareGlobal == XAResource.XA_OK)
if (l_doCommit)
l_xaResourceGlobal.commit(l_xidGlobal, false);
else
l_xaResourceGlobal.rollback(l_xidGlobal); // Close the Statements
l_stmtTravel.close();
l_stmtGlobal.close(); } catch(SQLException ex) { // Trap SQL Errors
System.out.println("Error in Updating"+ex.toString());
} catch (XAException xae) { // Trap Transaction Exception
System.out.println("Transaction Error"+xae.toString());
} finally { // return the connection objects to the pool
if (l_connectionTravel != null)
try {
l_connectionTravel.close();
} catch(SQLException e) { // Trap SQL Errors
System.out.println(e.toString());
}
if (l_connectionGlobal != null)
try {
l_connectionGlobal.close();
} catch(SQLException e) { // Trap SQL Errors
System.out.println(e.toString());
}
}
}
}
访问http://168.168.18.11:81/etechbase/advsearch.php将您的问题输入查询内容框,选择不同的精确程度,即可以找到你所需要的答案。效果还是可以的。