Java访问oracle数据库
1.准备jar包:ojdbc6.jar(在oracle的安装路径里面也有)
2.写测试代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class Demo { public static void main(String[] args) { Connection conn = null;// 创建一个数据库连接 PreparedStatement pre = null; // 创建预编译语句对象 ResultSet result = null; try { Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序 System.out.println("开始尝试连接数据库!"); String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE";// 数据库地址 String user = "scott";// 用户名 String password = "123456";// 密码 conn = DriverManager.getConnection(url, user, password);// 获取连接 System.out.println("连接成功!"); String sql = "select * from emp where job = ?"; pre = conn.prepareStatement(sql); pre.setString(1, "SALESMAN"); result = pre.executeQuery(); while (result.next()) { String name = result.getString("ename"); System.out.println("name is " + name); } } catch (Exception e1) { e1.printStackTrace(); } finally { try { // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源 // 注意关闭的顺序,最后使用的最先关闭 if (result != null) result.close(); if (pre != null) pre.close(); if (conn != null) conn.close(); System.out.println("数据库连接已关闭!"); } catch (Exception e2) { e2.printStackTrace(); } } } }