logo头像

小玉的技术博客

JAVA数据库连接之JDBC

前言

JDBC (Java Database Connectivity) API,即Java数据库编程接口,是连接java应用程序和数据库之间的桥粱,是一组标准的Java语言中的接口和类,使用这些接口和类,Java客户端程序可以访问各种不同类型的数据库。比如建立数据库连接、执行SQL语句进行数据的存取操作。

JDBC使用详解

1.加载驱动器类

2.建立与数据库的链接

3.创建statement对象

4.执行SQL语句

5.访问ResultSet的记录

6.依次关闭ResultSet、Statement、Connection对象

示例代码如下

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
67
68
69
70
71
72
73
74
75
76
77
78
79
public class DBUtil {
private static String DRIVER_NAME = null;
private static String URL = null;
private static String USER_NAME = null;
private static String PWD = null;
private static Properties properties = new Properties();
static {
try {
properties.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
}catch (IOException e) {
System.out.println("系统加载jdbc.properties配置文件异常");
}
DRIVER_NAME = properties.getProperty("jdbc.driver");
URL = properties.getProperty("jdbc.url");
USER_NAME = properties.getProperty("jdbc.username");
PWD = properties.getProperty("jdbc.password");
try {
Class.forName(DRIVER_NAME);
}catch (ClassNotFoundException e) {
System.out.println("数据库驱动加载异常,请检查");
}
}
public static Connection getConnection() {
// DriverManager.registerDriver(new Driver());
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER_NAME, PWD);
} catch (SQLException e) {
System.out.println(e);
System.out.println("连接数据库失败了");
}
return connection;
}
public static void close(Connection connection) {
close(connection);
}
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet !=null) {
try {
if (!resultSet.isClosed()) {
resultSet.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
if (connection !=null) {
try {
if (!connection.isClosed()) {
connection.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
if (statement !=null) {
try {
if (!statement.isClosed()) {
statement.close();
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
}

支付宝打赏 微信打赏

赞赏是不耍流氓的鼓励