1. 安装Oracle数据库,我这里使用的是Oracle 12c
2. 创建Java工程 connection-oracle
注意:使用的JavaSE-1.8
3. 在Oracle的安装目录里,将djdbc8.jar 拷贝到java工程
路径为:C:\app\oracle\product\12.2.0\dbhome_1\jdbc\lib
4. 创建连接Oracle的java类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
public
class
OracleJdbcTest {
//数据库连接对象
private
static
Connection conn =
null
;
private
static
String driver =
"oracle.jdbc.driver.OracleDriver"
;
//驱动
private
static
String url =
"jdbc:oracle:thin:@//127.0.0.1:1521/orcl"
; //连接字符串
private
static
String username =
"system"
;
//用户名
private
static
String password =
"123456"
;
//密码
// 获得连接对象
private
static
synchronized
Connection getConn(){
if
(conn ==
null
){
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
return
conn;
}
//执行查询语句
public
void
query(String sql,
boolean
isSelect)
throws
SQLException{
PreparedStatement pstmt;
try
{
pstmt = getConn().prepareStatement(sql);
//建立一个结果集,用来保存查询出来的结果
ResultSet rs = pstmt.executeQuery();
while
(rs.next()) {
String name = rs.getString(
"name"
);
System.out.println(name);
}
rs.close();
pstmt.close();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
public
void
query(String sql)
throws
SQLException{
PreparedStatement pstmt;
pstmt = getConn().prepareStatement(sql);
pstmt.execute();
pstmt.close();
}
//关闭连接
public
void
close(){
try
{
getConn().close();
}
catch
(SQLException e) {
e.printStackTrace();
}
}
}
|
5. 创建调用类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public
class
ConnOracle {
public
static
void
main(String[] args)
throws
SQLException {
OracleJdbcTest test =
new
OracleJdbcTest();
try
{
test.query(
"drop table student"
);
}
catch
(SQLException e) {}
test.query(
"create table student(id int, name nchar(20))"
);
test.query(
"insert into student values(1,'zhangsan')"
);
test.query(
"insert into student values(2,'lisi')"
);
test.query(
"select * from student"
,
true
);
test.close();
}
}
|
6. 显示结果
本文转自work hard work smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/8215677.html,如需转载请自行联系原作者