数据库连接工具类

mysql数据库连接类

首先在maven项目的 pom 文件添加以下依赖

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>

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
/**
* @description: 数据库连接工具类
* @author: xxzuo
* @email: 1293378490@qq.com
* @date: 2022/6/17 14:42
**/
public class DbUtils {
private static DruidDataSource dataSource;

public static Connection getConnection() throws Exception {
dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/xxxxx");
dataSource.setUsername("root");
dataSource.setPassword("123456");
//设置初始化连接数,最大连接数,最小闲置数
dataSource.setInitialSize(10);
dataSource.setMaxActive(50);
dataSource.setMinIdle(5);
//返回连接
return dataSource.getConnection();
}

public static Connection getConnection(String jdbc, String userName, String password) throws Exception {
dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(jdbc);
dataSource.setUsername(userName);
dataSource.setPassword(password);
//设置初始化连接数,最大连接数,最小闲置数
dataSource.setInitialSize(10);
dataSource.setMaxActive(50);
dataSource.setMinIdle(5);
//返回连接
return dataSource.getConnection();
}
}

调用方法

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
try (Connection connection = DbUtils.getConnection()) {
String sql = "SELECT COL_NAME FROM TABLE_NAME";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
rs.getString("COL_NAME");
}
} catch (Exception e) {

}
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!