00时 00分 00秒

Java连接Oracle数据库

1、使用XE数据库,建立employees用户,密码为123456

/*
首先在system用户下
*/
create user employees identified by 123456;
grant connect to employees;
grant resource to employees;
conn employees/123456;

create table emp
(
emp_no number(4) primary key,
e_name varchar2(10),
job varchar2(9),
mgr number(4),
hiredate date,
sal number(7,2),
comm number(7,2),
dept_no number(4)
);

insert into emp values
(7369,'SMITH','CLERK',7902,TO_DATE('17-12-1980','dd-mm-yyyy'),800,null,20);
insert into emp values
(7499,'ALLEN','SALESMAN',7698,TO_DATE('20-2-1981','dd-mm-yyyy'),1600,300,30);
insert into emp values
(7521,'WARD','SALESMAN',7698,TO_DATE('22-2-1981','dd-mm-yyyy'),1250,500,30);
insert into emp values
(7566,'JONES','MANAGER',7839,TO_DATE('2-4-1981','dd-mm-yyyy'),2975,NULL,20);
insert into emp values
(7654,'MARTIN','SALESMAN',7698,TO_DATE('28-9-1981','dd-mm-yyyy'),1250,1400,30);
insert into emp values
(7698,'BLAKE','MANAGER',7839,TO_DATE('1-5-1981','dd-mm-yyyy'),2850,NULL,30);
insert into emp values
(7782,'CLARK','MANAGER',7839,TO_DATE('9-6-1981','dd-mm-yyyy'),2450,NULL,10);
insert into emp values
(7839,'KING','PRESIDENT',NULL,TO_DATE('17-11-1981','dd-mm-yyyy'),5000,NULL,10);
insert into emp
values(7788,'SCOTT','ANALYST',7566,'19-4月-1987',3000.00,NULL,20);
insert into emp values
(7844,'TURNER','SALESMAN',7698,TO_DATE('8-9-1981','dd-mm-yyyy'),1500,0,30);
insert into emp values
(7900,'JAMES','CLERK',7698,TO_DATE('3-12-1981','dd-mm-yyyy'),950,NULL,30);
insert into emp values
(7902,'FORD','ANALYST',7566,TO_DATE('3-12-1981','dd-mm-yyyy'),3000,NULL,20);
insert into emp values
(7934,'MILLER','CLERK',7782,TO_DATE('23-1-1982','dd-mm-yyyy'),1300,NULL,10);

2、编写Java文件

//演示如何使用Java连接Oracle
package com.tfj.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JavaCtOracle {
    public static void main(String[] args) {
        try {
            // 1.加载驱动
            Class.forName("oracle.jdbc.driver.OracleDriver");
            // 2.得到链接
            Connection ct = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
                    "employees", "123456");
            // 2.跟sql server一模一样,Sql语句
            Statement sm = ct.createStatement();
            ResultSet rs = sm.executeQuery("select * from emp");
            while (rs.next()) {
                // 用户名
                System.out.println("用户名:" + rs.getString(2));
            }
            // 关闭打开的资源
            rs.close();
            sm.close();
            ct.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2015-10-27 15:21  杰克思勒(Jacksile)  阅读(311)  评论(0编辑  收藏  举报