import java.sql.*;
/**
* <p>Title: JDBC連接數據庫</p>
* <p>Description: 本實例演示如何使用JDBC連接Oracle數據庫,並演示添加數據和查詢數據。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: JDBCConn.java</p>
* @version 1.0
*/
public class JDBCConn{
private String url="";
private String username="";
private String password="";
/**
*<br>方法說明:獲得數據連接
*<br>輸入參數:
*<br>返回類型:Connection 連接對象
*/
public Connection conn(){
try {
//加載JDBC驅動
Class.forName("oracle.jdbc.driver.OracleDriver");
//創建數據庫連接
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL", "test", "test");
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>方法說明:執行查詢SQL語句
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String sql 要執行的SQL語句
*<br>返回類型:
*/
public void query(Connection con, String sql){
try{
if(con==null){
throw new Exception("database connection can´t use!");
}
if(sql==null) throw new Exception("check your parameter: ´sql´! don´t input null!");
//聲明語句
Statement stmt = con.createStatement();
//執行查詢
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rmeta = rs.getMetaData();
//獲得數據字段個數
int numColumns = rmeta.getColumnCount();
while(rs.next())
{
for(int i = 0;i< numColumns;i++)
{
String sTemp = rs.getString(i+1);
System.out.print(sTemp+" ");
}
System.out.println("");
}
}catch(Exception e){
System.out.println("query error:"+e);
}
}
/**
*<br>方法說明:執行插入、更新、刪除等沒有返回結果集的SQL語句
*<br>輸入參數:Connection con 數據庫連接
*<br>輸入參數:String sql 要執行的SQL語句
*<br>返回類型:
*/
public void execute(Connection con, String sql){
try{
if(con==null) return;
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
System.out.println("execute error: sql = "+sql);
System.out.println(e);
}
}
/**
*<br>方法說明:實例演示
*<br>輸入參數:
*<br>返回類型:
*/
public void demo(){
try{
JDBCConn oc = new JDBCConn();
Connection conn = oc.conn();
String sql = "insert into TBL_USER(id,name,password)values(seq_user.nextval,´switch´,´haorenpingan´)";
oc.execute(conn,sql);
sql = "select * from TBL_USER";
oc.query(conn,sql);
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 JDBCConn url username password");
return;
}
JDBCConn oc = new JDBCConn();
oc.url = arg[0];
oc.username=arg[1];
oc.password=arg[2];
oc.demo();
}
}