import java.sql.*; public class TestJDBC { // orcl为oracle数据库中的数据库名,localhost表示连接本机的oracle数据库 // 1521为连接的端口号 private static String url = "jdbc:oracle:thin:@localhost:1521:ORCL"; // scott为登陆oracle数据库的用户名 private static String user = "scott"; // tiger为用户名scott的密码 private static String password = "tiger"; public static void main(String[] args) throws Exception { Connection conn = null ; Statement stm = null; ResultSet rs = null; try { //1、注册:方法一 Class.forName("oracle.jdbc.driver.OracleDriver"); /* //注册:方法二 new oracle.jdbc.driver.OracleDriver(); */ //2、连接 conn = DriverManager.getConnection(url,user,password); if (conn == null) { System.out.println("connect fail with Oracle!"); } else { System.out.println("connect success with Oracle!"); } //3.将数据发送到数据库中 stm = conn.createStatement(); //4.执行语句 rs = stm.executeQuery("select * from emp;"); //5.显示语句 while (rs.next()) { System.out.println(rs.getString("ename")); } } catch (ClassNotFoundException e) { //将异常信息打印到日志中 e.printStackTrace(); }finally{ try { if (rs != null) { rs.close(); rs = null;//确保垃圾回收器可以及时回收已不再使用的实例对象 } if (stm != null) { stm.close(); stm = null;//同上 } if (conn != null) { conn.close(); conn = null;//同上 } } catch (SQLException e) { //将异常信息打印到log中 e.printStackTrace(); } } } }