在Java开发中,与数据库进行交互是几乎每个项目都离不开的功能。JDBC(Java DataBase Connectivity)作为Java操作数据库的标准规范,为开发者提供了底层的数据库访问支持。而数据库连接池则是提高数据库操作效率和性能的重要工具。本文将结合实际代码示例,带你深入浅出地了解JDBC和数据库连接池的知识与应用。
JDBC 是一组 Java API,它允许 Java 程序与各种关系型数据库进行交互。通过 JDBC,我们可以连接到数据库、执行 SQL 语句、处理查询结果等操作。JDBC 的核心类和接口主要集中在 java.sql
和 javax.sql
包中。
注册驱动 :告知程序要使用的数据库驱动。
早期做法为使用 DriverManager.registerDriver(new DriverImpl())
,但这种方式可能会导致驱动被注册两次。
推荐做法是使用 Class.forName("数据库驱动类名")
,例如 Class.forName("com.mysql.jdbc.Driver")
,这种方式会自动加载驱动。
获取数据库连接 :通过 DriverManager.getConnection(url, username, password)
方法获取连接。其中,url 指定数据库的连接地址,如 jdbc:mysql://localhost:3306/数据库名
。
创建 Statement 对象 :使用 Connection.createStatement()
方法创建,用于执行 SQL 语句。
执行 SQL 语句 :
查询操作:调用 Statement.executeQuery(sql)
方法执行查询,返回 ResultSet
对象,其中包含查询结果。
增删改操作:调用 Statement.executeUpdate(sql)
方法执行,返回受影响的行数。
处理结果集(针对查询操作) :通过 ResultSet
对象提供的方法(如 next()
、getInt()
、getString()
等)遍历查询结果并获取数据。
释放资源 :按照 resultSet → statement → connection 的顺序依次关闭,避免资源泄漏。通常在 finally 块中进行关闭操作。
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
connection = DriverManager.getConnection("jdbc:mysql:///spring_db", "root", "2020");
// 创建 Statement
statement = connection.createStatement();
// 执行查询
String sql = "select * from account";
resultSet = statement.executeQuery(sql);
// 处理结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double money = resultSet.getDouble("money");
System.out.println("id: " + id + ", name: " + name + ", money: " + money);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
为了简化 JDBC 操作代码,提高代码的可维护性和复用性,通常会编写 JDBC 工具类。工具类可以封装注册驱动、获取连接、关闭资源等公共操作。
将数据库连接的相关信息(如驱动类名、url、用户名、密码等)配置在 properties 文件中,工具类通过读取配置文件来获取这些信息,使代码更具灵活性,便于后期修改。
driverclass=com.mysql.jdbc.Driver
url=jdbc:mysql:///spring_db
username=root
password=2020
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils2 {
private static final String driverclass;
private static final String url;
private static final String username;
private static final String password;
static {
Properties properties = new Properties();
InputStream inputStream = JdbcUtils2.class.getResourceAsStream("/db.properties");
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
driverclass = properties.getProperty("driverclass");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
public static void createDriver() {
try {
Class.forName(driverclass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
createDriver();
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection, ResultSet resultSet, Statement statement) throws SQLException {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
public static void close(Connection connection, Statement statement) throws SQLException {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
事务是数据库中一系列操作的集合,这些操作要么全部成功,要么全部失败回滚。事务具有 ACID 特性:
原子性(Atomicity) :事务中的操作不可分割,要么全部执行,要么全部不执行。
一致性(Consistency) :事务执行前后,数据库始终处于一致的状态,符合业务规则和完整性约束。
隔离性(Isolation) :多个事务并发执行时,相互之间不会产生干扰,一个事务的执行不能被其他事务干扰。
持久性(Durability) :一旦事务提交,其对数据库的修改将永久保存,即使系统发生故障也不会丢失。
在 JDBC 中,通过 Connection
对象来管理事务。
开启事务 :调用 connection.setAutoCommit(false)
方法,将自动提交模式设置为 false,从而开启事务。
提交事务 :调用 connection.commit()
方法提交事务,使事务中的所有操作永久生效。
回滚事务 :调用 connection.rollback()
方法回滚事务,撤销事务中的所有操作,使数据库回到事务开始前的状态。
不同的事务隔离级别可以解决不同的并发问题:
读未提交(Read Uncommitted) :最低的隔离级别,事务可以读取其他事务未提交的数据,可能导致脏读、不可重复读和幻读问题。
读已提交(Read Committed) :事务只能读取其他事务已经提交的数据,避免了脏读,但可能仍然存在不可重复读和幻读问题。
可重复读(Repeatable Read) :保证事务在多次读取同一数据时,结果一致,避免了脏读和不可重复读,但可能出现幻读问题。这是 MySQL 的默认隔离级别。
串行化(Serializable) :最高的隔离级别,通过强制事务串行执行,避免了脏读、不可重复读和幻读问题,但性能开销较大。
在 JDBC 中,可以通过 connection.setTransactionIsolation(level)
方法设置事务的隔离级别,其中 level 是上述隔离级别的对应常量。
数据库连接池是应用程序与数据库之间的一组数据库连接的缓存。它预先创建并维护一定数量的数据库连接,当应用程序需要执行数据库操作时,可以从连接池中获取空闲连接,使用完毕后将连接归还到连接池中,而不是直接关闭连接。这样可以避免频繁地创建和销毁数据库连接所带来的性能开销,提高数据库操作的效率。
DBCP(Database Connection Pool) :Apache 提供的开源连接池,配置简单,但在高并发场景下性能表现一般。
C3P0 :另一个开源连接池,提供了自动回收空闲连接等功能,配置较为灵活。
Druid :阿里巴巴开源的数据库连接池,功能强大、性能优秀,还提供了监控和分析数据库访问性能的能力。
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///spring_db
username=root
password=2020
initialSize=5
maxActive=10
maxWait=3000
maxIdle=6
minIdle=3
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.io.*;
import java.sql.*;
import java.util.Properties;
public class JdbUtils3 {
private static DataSource dataSource;
static {
Properties properties = new Properties();
InputStream inputStream = JdbcUtils2.class.getResourceAsStream("/druid.properties");
try {
properties.load(inputStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection, ResultSet resultSet, Statement statement) throws SQLException {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
public static void close(Connection connection, Statement statement) throws SQLException {
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
性能提升 :减少了数据库连接的创建和销毁时间,提高了数据库操作的响应速度。
资源复用 :连接池中的连接可以被多个应用程序或线程复用,避免了资源的浪费。
管理方便 :连接池提供了对连接的统一管理,可以方便地设置最大连接数、最小连接数、超时时间等参数,以适应不同的应用场景和负载需求。
总的来说,JDBC 是 Java 操作数据库的基础,而数据库连接池则是提升数据库操作性能的关键。在实际开发中,我们通常会结合使用 JDBC 和连接池,以实现高效、稳定、可靠的数据库访问。通过合理地配置和使用连接池,可以充分发挥其优势,提高系统的整体性能和可扩展性。