標籤:
import java.sql.*;import java.util.ArrayList;import java.util.List;//使用jdbc串連public class TestOra { public static void main(String[] args) { // TODO Auto-generated method stub BaseDao basedao = new BaseDao(); Connection conn = basedao.getConnection(); basedao.add(conn); basedao.delete(conn); basedao.update(conn); basedao.query(conn); basedao.close(); }}class BaseDao { private static String url = "jdbc:oracle:thin:@localhost:1521:orcl"; private static String user = "c##scott"; private static String password = "tiger"; private Connection conn; private static Statement sm; private static ResultSet rs; private static String sql; // 串連資料庫函數 public Connection getConnection() { try { // 初始化驅動包 Class.forName("oracle.jdbc.OracleDriver"); // 根據資料庫連接字元,名稱,密碼給conn System.out.println("開始嘗試串連資料庫!"); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } return conn; } // 查詢函數 public void query(Connection conn) { sql = "select * from EMP"; try { sm = conn.createStatement(); rs = sm.executeQuery(sql); while (rs.next()) { System.out.println("ID: " + rs.getString(1) + "\tNAME: " + rs.getString(2) + "\tAGE: " + rs.getString(3)); } } catch (Exception e) { e.printStackTrace(); } } // 添加表資料 public void add(Connection conn) { sql = "insert into EMP(ID,NAME,AGE)" + " values (‘0005‘,‘lucyyyy‘,‘14‘)"; try { sm = conn.createStatement(); sm.executeUpdate(sql); System.out.println("添加成功"); } catch (Exception e) { e.printStackTrace(); } } // 刪除資料 public void delete(Connection conn) { sql = "delete from EMP " + "where ID=‘2‘"; try { sm = conn.createStatement(); sm.executeUpdate(sql); System.out.println("刪除成功"); } catch (Exception e) { e.printStackTrace(); } } // 修改資料 public void update(Connection conn) { sql = "update EMP set ID=‘2‘ where NAME=‘lucy‘"; try { sm = conn.createStatement(); sm.executeUpdate(sql); System.out.println("更新成功"); } catch (Exception e) { e.printStackTrace(); } } public void close() {// 6.釋放資源 try { // 捕捉異常 try { if (rs != null) { // 當ResultSet對象的執行個體rs不為空白時 rs.close(); // 關閉ResultSet對象 } } finally { try { if (sm != null) { // 當Statement對象的執行個體stmt不為空白時 sm.close(); // 關閉Statement對象 } } finally { if (conn != null) { // 當Connection對象的執行個體conn不為空白時 conn.close(); // 關閉Connection對象 } } } } catch (Exception e) { e.printStackTrace(System.err); // 輸出異常資訊 } }}
java實現oracle資料庫基本操作