Java连接数据库:异常处理与优化
在Java中,连接数据库主要使用JDBC(Java Database Connectivity)接口。以下是一个简单的示例,包括异常处理和优化:
- 异常处理:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DB_URL = “jdbc//localhost:3306/mydatabase”;
private static final String USER = “username”;
private static final String PASSWORD = “password”;
public static Connection getConnection() throws SQLException {
Connection connection = null;
try {
// 注册JDBC驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
connection = DriverManager.getConnection(DB_URL, USER, PASSWORD));
if (connection != null) {
System.out.println("Database connection successful.");
}
} catch (Exception e) {
System.err.println("Error occurred while connecting to database: " + e.getMessage());
if (connection != null) {
connection.close();
}
throw new SQLException(e.getMessage(), e));
}
return connection;
}
// 优化:使用连接池
private static final Object POOL_LOCK = new Object();
private static ConnectionPool getConnectionPool() throws SQLException {
ConnectionPool pool = null;
synchronized (POOL_LOCK) {
if (pool == null) {
// 初始化连接池
pool = new SimpleConnectionPool();
}
}
return pool.getConnection();
}
public static void main(String[] args) {
try {
// 使用优化后的连接池
Connection connection = getConnectionPool().getConnection();
if (connection != null) {
System.out.println("Database connection successful.");
// 处理数据库操作...
} else {
System.out.println("Connection to database pool failed.");
}
} catch (SQLException e) {
System.err.println("Error occurred while connecting to database: " + e.getMessage());
if (connection != null) {
connection.close();
}
throw new RuntimeException(e.getMessage(), e));
}
}
}
```
- 优化:
- 使用连接池(如
SimpleConnectionPool
)来管理数据库连接,避免频繁创建和销毁连接。 - 当出现异常时,确保关闭数据库连接,防止资源泄露。
这只是一个基本示例,实际使用中可能需要根据数据库类型、配置等进行调整。
还没有评论,来说两句吧...