import java.sql.*;
/**
* <p>Title: JDBC連接數據庫</p>
* <p>Description: 本實例演示如何使用JDBC連接Oracle數據庫,並演示添加數據和查詢數據。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: JDBCSTMConn.java</p>
* @version 1.0
*/
public class JDBCSTMConn{
private static String url="";
private static String username="";
private static String password="";
/**
*<br>方法說明:獲得數據連接
*<br>輸入參數:
*<br>返回類型:Connection 連接對象
*/
public Connection conn(){
try {
//加載JDBC驅動
Class.forName("oracle.jdbc.driver.OracleDriver");
//創建數據庫連接
Connection con = DriverManager.getConnection(url, username, password);
return con;
}catch(ClassNotFoundException cnf){
System.out.println("driver not find:"+cnf);
return null;
}catch(SQLException sqle){
System.out.println("can´t connection db:"+sqle);
return null;
} catch (Exception e) {
System.out.println("Failed to load JDBC/ODBC driver.");
return null;
}
}
/**
*<br>方法說明:調用存儲過程,察看數據結果
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String sql 要執行的SQL語句
*<br>返回類型:
*/
public void execute(Connection con){
CallableStatement toesUp = null;
try {
con.setAutoCommit(false);
//調用存儲過程
toesUp = con.prepareCall("{call p_test(?)}");
//傳遞參數給存儲過程
toesUp.setInt(1, 6);
//執行存儲過程
toesUp.executeQuery();
Statement stmt = con.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery("SELECT * FROM TEST");
while (rs.next()) {
String ID = rs.getString(1);
String NAME = rs.getString(2);
System.out.println(ID+ " " +NAME);
}
rs.close();
} catch (SQLException e) {
System.out.println(e);
try{
toesUp.close();
con.close();
}catch(Exception es){System.out.println(es);}
}
}
/**
*<br>方法說明:實例演示
*<br>輸入參數:
*<br>返回類型:
*/
public void demo(){
try{
JDBCSTMConn oc = new JDBCSTMConn();
Connection conn = oc.conn();
oc.execute(conn);
conn.close();
}catch(SQLException se){
System.out.println(se);
}catch(Exception e){
System.out.println(e);
}
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] arg){
if(arg.length!=3){
System.out.println("use: java JDBCSTMConn url username password");
return;
}
JDBCSTMConn oc = new JDBCSTMConn();
oc.url = arg[0];
oc.username=arg[1];
oc.password=arg[2];
oc.demo();
}
}