1. Import the driver package:
A. Locate the file Classes12.jar in the Jdbc/lib under the Oracle installation directory;
B. Right-click the Java project you created, find the build path, choose Add External Archives, Find the package you want to import Classes12.jar, click Open can be introduced, after the introduction of the project under the Referencedelibraries can display this package.
2. Code testing:
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
importjava.sql.*;publicclassoracle{ String driver = "oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:orcl";//@主机名:监听端口:数据库实例名称,Attention notes:the port is generally 1521 String name = "system";//登录名 String pwd = "orcl";//登陆密码 privatestaticStatement sql = null; privatestaticResultSet rs = null; privatestaticConnection con = null; publicConnection getCon() { try { Class.forName(driver); //注册oracle数据库驱动 } catch(ClassNotFoundException e1) { System.out.println("驱动加载失败!"); e1.printStackTrace(); } try { con = DriverManager.getConnection(url, name, pwd);//获取连接字符串 } catch(SQLException e) { System.out.println("驱动或数据库连接失败!"); e.printStackTrace(); } returncon; } publicstaticvoidmain(String[] args) { try { oracle db = neworacle(); Connection con = db.getCon(); if (con != null) { System.out.println("数据库连接成功!"); } else { System.out.println("数据库连接失败!"); } sql = con.createStatement(); rs = sql.executeQuery("select * from students"); System.out.println("编号\t学号\t姓名\t性别\t出生日期"); while(rs.next()) { System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getString(5)); } } catch(Exception e) { e.printStackTrace(); } }} |
3. Test results:
Java Connection oracle10g