首页 > 学院 > 开发设计 > 正文

Java连接Oracle数据库

2019-11-15 01:14:01
字体:
来源:转载
供稿:网友
java连接Oracle数据库
 1     package com.db;   2        3     import java.sql.Connection;   4     import java.sql.DriverManager;   5     import java.sql.PReparedStatement;   6     import java.sql.ResultSet;   7        8     public class DBConnection {   9         // 连接Oracle数据库  10         public void OracleConnection() {  11             Connection con = null;  12             PreparedStatement pre = null;  13             ResultSet rs = null;  14       15             try {  16                 // 1. 加载Oracle驱动程序  17                 Class.forName("oracle.jdbc.driver.OracleDriver");  18                   19                 // 2. 设置Oracle数据库基本信息  20                 String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";  21                 String user = "scott";  22                 String passWord = "goodluck";  23       24                 // 2. 获取连接  25                 con = DriverManager.getConnection(url, user, password);  26                 System.out.println("----> Connection Success!");  27       28                 // 3. 执行SQL语句  29                 String sql = "SELECT * FROM EMP";  30                 pre = con.prepareStatement(sql);  31       32                 // 4. 获取结果集  33                 rs = pre.executeQuery();  34                 while (rs.next()) {  35                     System.out.println("编号:" + rs.getString("empno")   36                                     + ";姓名:" + rs.getString("ename")  37                                     + "; 工作:" + rs.getString("job")  38                                     + "; 领导:" + rs.getString("mgr")  39                                     + "; 雇佣日期:" + rs.getString("hiredate")  40                                     + "; 工资:" + rs.getString("sal")  41                                     + "; 奖金:" + rs.getString("comm")  42                                     + "; 部门:" + rs.getString("deptno"));  43                 }  44             } catch (Exception e) {  45                 e.printStackTrace();  46             } finally {  47                 try {  48                     if (rs != null)  49                         rs.close();  50                     if (pre != null)  51                         pre.close();  52                     if (con != null)  53                         con.close();  54                     System.out.println("----> Connection End <-----");  55                 } catch (Exception e) {  56                     e.printStackTrace();  57                 }  58             }  59         }  60       61         public static void main(String[] args) {  62             DBConnection db = new DBConnection();  63             db.OracleConnection();  64         }  65     }  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表