数据库连接管理--Java连接数据库的几种方式
1.数据库连接管理
1.1 使用JDBC获取连接
JDBC是Java标准库提供的API,用于连接和操作关系型数据库。它是最基础、最常用的数据库连接方式。
步骤:
- 加载数据库驱动。
- 建立连接。
- 创建Statement或PreparedStatement对象。
- 执行SQL查询或更新。
- 处理结果集。
- 关闭连接。
private static final String URL = "jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "226774";
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 1. 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 建立数据库连接
connection = DriverManager.getConnection(URL, USER, PASSWORD);
// 3. 创建 PreparedStatement 并设置参数
String sql = "SELECT id,`name`,species,age FROM pets WHERE age > ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,"3");
// 4. 执行查询
resultSet = preparedStatement.executeQuery();
// 5. 处理结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String species = resultSet.getString("species");
int age = resultSet.getInt("age");
System.out.println("ID: " + id + ", Name: " + name +",Species"+species+ ", Age: " + age);
}
} catch (ClassNotFoundException e) {
System.err.println("数据库驱动未找到: " + e.getMessage());
} catch (SQLException e) {
System.err.println("数据库连接失败: " + e.getMessage());
} finally {
// 6. 关闭资源
try {
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
System.err.println("资源关闭失败: " + e.getMessage());
}
}
}
由于获取数据库连接资源比较繁琐,因此要对数据库连接进行管理。
对数据库连接进行配置化管理连接串,用户名,密码以及驱动类,配置化管理就是把相关的字符串放入到一个文件中,这个文件可以是接口,可以是properties文件,可以是xml文件。
1.2 使用接口方法获取连接
1.创建接口
public interface DBconfig {
//把连接的地址,用户名,密码作为常量封装到接口中
public static final String URL = "jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC";
public static final String USER = "root";
public static final String PASSWORD = "226774";
}
2.创建连接工具类
public class ConnectionHelp {
//静态代码块,调用类时只加载一次
static{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//构造私有化,不能再创建ConnectionHelp对象
private ConnectionHelp(){
}
//创建数据库连接,封装到方法中
public static Connection getCon() throws SQLException {
Connection connection = DriverManager.getConnection(DBconfig.URL,DBconfig.USER,DBconfig.PASSWORD);
return connection;
}
}
3.调用连接并测试查询语句
public class TestConnection {
public static void main(String[] args) throws SQLException {
//调用连接方法
ConnectionHelp.getCon();
String sql = "select * from pets where id = ?";
PreparedStatement preparedStatement = ConnectionHelp.getCon().prepareStatement(sql);
preparedStatement.setInt(1,1);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String name = resultSet.getString("name");
String species = resultSet.getString("species");
int age = resultSet.getInt("age");
System.out.println("姓名:"+name + " \t种类:" + species + " \t年龄:" + age);
}
}
}
1.3 使用properties文件获取连接
properties文件是一个文本文件,用key=value这样的方法进行保存数据,由于不需要编译,所以在idea中,要放入到资源文件夹(scr/main/resources)中。
1.创建config.properties配置文件
driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/pet_management?useSSL=false&serverTimezone=UTC
username=root
userpass=226774
2.创建链接工具类
private static String driverName;
private static String url;
private static String userName;
private static String userPass;
static{
InputStream in = ConnectionHelp2.class.getResourceAsStream("/conf.properties");
Properties prop = new Properties();
try {
prop.load(in);
driverName = prop.getProperty("driverName");
url = prop.getProperty("url");
userName = prop.getProperty("username");
userPass = prop.getProperty("userpass");
Class.forName(driverName);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private ConnectionHelp2(){
}
public static Connection getCon() throws SQLException {
Connection connection = DriverManager.getConnection(url,userName,userPass);
return connection;
}
3.调用连接并测试
此处与方法2相同,不同的是连接工具类的差异,以及调用时使用的连接工具类不同ConnectionHelp2.getCon();
public static void main(String[] args) throws SQLException {
ConnectionHelp2.getCon();
String sql = "select * from pets where id = ?";
PreparedStatement preparedStatement = ConnectionHelp2.getCon().prepareStatement(sql);
preparedStatement.setInt(1,1);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String name = resultSet.getString("name");
String species = resultSet.getString("species");
int age = resultSet.getInt("age");
System.out.println("姓名:"+name + " \t种类:" + species + " \t年龄:" + age);
}
}
4.扩展:使用第三方组件读取properties文件
第三方组件:非java的jdk提供的标准类,由非官方提供的类功能包
建议看一个第三方包,国产组件:hutool,指南位置:https://plus.hutool.cn/pages/index/
使用第三方组件的标准流程
1.要根据官网/maven依赖查询网址,把组件依赖添加到项目中
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.35</version>
</dependency>
2.使用hutool进行数据库连接的方法
Props props = new Props("conf.properties");
System.out.println(props.getStr("driverName"));
Props props = new Props("conf.properties");
// 从属性文件中获取属性
String driver = props.getStr("driverName");
String url = props.getProperty("url");
String user = props.getProperty("username");
String pass = props.getProperty("userpass");
// 加载驱动
Class.forName(driver);
//创建与数据库的连接
Connection connection = DriverManager.getConnection(url,user,pass);
1.4 使用数据库连接池
1.什么是连接池
连接池(Connection Pool)是一种用于管理数据库连接的技术。它的核心思想是预先创建并维护一组数据库连接,当应用程序需要与数据库交互时,从连接池中获取一个连接,使用完毕后将连接归还给连接池,而不是每次都创建新的连接或关闭连接。
2.为什么使用连接池
在传统的数据库连接方式中,每次与数据库交互时都需要创建新的连接,使用完毕后关闭连接。这种方式存在以下问题:
性能开销大:创建和关闭数据库连接是非常耗时的操作,频繁地创建和关闭连接会严重影响系统性能。
资源浪费:数据库连接是有限的资源,频繁创建和关闭连接会导致资源浪费,甚至可能导致数据库连接耗尽。
难以管理:在高并发场景下,频繁创建和关闭连接会导致数据库连接数激增,增加数据库的负担。
连接池通过复用数据库连接,解决了上述问题:
减少创建和关闭连接的开销:连接池中的连接是预先创建好的,应用程序直接从连接池中获取连接,使用完毕后归还,避免了频繁创建和关闭连接的开销。
提高资源利用率:连接池中的连接可以被多个请求复用,减少了资源浪费。
控制连接数:连接池可以限制最大连接数,避免数据库连接数过多导致数据库崩溃。
3.如何理解连接池
可以将连接池类比为“共享单车”:
1.连接池:就像一个共享单车停放点,里面停放着一定数量的单车(数据库连接)。
2.应用程序:就像需要使用单车的人。
3.获取连接:当应用程序需要与数据库交互时,从连接池中“借”一辆单车(获取一个连接)。
4.使用连接:应用程序使用这个连接与数据库交互。
5.归还连接:使用完毕后,应用程序将连接“归还”给连接池,而不是销毁它。
通过这种方式,连接池实现了连接的复用,避免了频繁创建和关闭连接的开销。
4.使用druid连接池的步骤
步骤一:下载依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
步骤二:编写配置文件,注意根据本地的配置进行修改
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/pet_management
username=root
password=226774
InitialSize=5
MaxActive=20
MaxWait=3000
步骤三:把配置文件导入到连接池类中
public static DataSource dataSource;
static {
Props props = new Props("druid.properties");
try {
dataSource = DruidDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Connection getCon() throws SQLException {
return dataSource.getConnection();
}