JDBC连接Oracle数据库的示例代码

原文地址:https://blog.csdn.net/sinat_27933301/article/details/78547346

1、DBUtil类
package tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* JDBC连接Oracle数据库的示例代码
* @author:yunfan
* */

public class DBUtil{
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();// 加载Oracle驱动程序
System.out.println("oracle驱动程序加载中!");
}
catch(InstantiationException e1)
{
System.out.println("实例异常");
}
catch(IllegalAccessException e2)
{
System.out.println("访问异常");
}
catch(ClassNotFoundException e3)
{
System.out.println("MySQL驱动类找不到");
}
}

/***
* 返回一个数据库连接
*/
public static Connection getConnection()
{
Connection connection = null;// 创建一个数据库连接
try
{
System.out.println("开始尝试连接数据库!");
String url = "jdbc:oracle:thin:@127.0.0.1:1521:oracle";//Oracle的默认数据库名
String user = "system";// 系统默认的用户名
String password = "system";// 安装时设置的密码
connection = DriverManager.getConnection(url, user, password);// 获取连接
System.out.println(url);
System.out.println("用户名:"+user+" "+"密码:******");
System.out.println("数据库连接成功!");
return connection;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
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
2、ConnectTest类
package tools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectTest {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet result = null;
try {
connection = DBUtil.getConnection();
String sql = "select * from user where id = ?";
ps = connection.prepareStatement(sql);
ps.setInt(1, 1);
result = ps.executeQuery();
while (result.next()) {
System.out.println(result.getInt("id") + " 用户名:"
+ result.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
// 注意关闭的顺序,最后使用的最先关闭
if (result != null) {
result.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
System.out.println("数据库连接已关闭!");
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

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
控制台输出:
oracle驱动程序加载中!
开始尝试连接数据库!
jdbc:oracle:thin:@127.0.0.1:1521:oracle
用户名:system 密码:******
数据库连接成功!
1 用户名:yunfan
数据库连接已关闭!