import java.sql.*; public class HelloJava { public static void main(String[] args) { OracleLink(); } public static void OracleLink() { Connection con = 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:orcl"; String user = "scott"; String password = "scott"; con = DriverManager.getConnection(url, user, password); System.out.println("连接成功!"); // 查询 String sql = "SELECT * FROM test where name=?"; //?代表参数 pre = con.prepareStatement(sql); //实例化预编译语句 pre.setString(1,"张三"); //1表示参数索引 result = pre.executeQuery(); while (result.next()) { System.out.println("结果为:" + result.getString("NAME")); } // 插入 // String sql="insert into ... values()"; // pre=con.prepareStatement(sql); // pre.execute(); // con.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { //关闭对象,最后使用的最先关闭 if (result != null) result.close(); if (pre != null) pre.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } }