写一个Jdbc程序,使用Druid包实现增删改查功能,正确回收连接
时间: 2024-12-22 19:12:58 浏览: 3
要编写一个使用Druid包的JDBC程序来实现增删改查操作并确保正确回收连接,首先你需要添加Druid依赖,并设置其配置。以下是一个简单的示例:
```java
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DruidJdbcExample {
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "username";
private static final String PASS = "password";
// 创建DruidDataSource实例
private static final DruidDataSource dataSource = new DruidDataSource();
static {
dataSource.setUrl(DB_URL);
dataSource.setUsername(USER);
dataSource.setPassword(PASS);
dataSource.init(); // 初始化数据源
}
public void CRUDOperations() {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 获取连接
conn = dataSource.getConnection();
// 插入操作
String insertSql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
pstmt = conn.prepareStatement(insertSql);
pstmt.setString(1, "value1");
pstmt.setString(2, "value2");
pstmt.executeUpdate();
// 查询操作
String selectSql = "SELECT * FROM table_name WHERE column1 = ?";
pstmt = conn.prepareStatement(selectSql);
pstmt.setString(1, "value1");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("column1"));
}
// 更新操作
String updateSql = "UPDATE table_name SET column1 = ? WHERE id = ?";
pstmt = conn.prepareStatement(updateSql);
pstmt.setString(1, "new_value");
pstmt.setInt(2, 1);
pstmt.executeUpdate();
// 删除操作
String deleteSql = "DELETE FROM table_name WHERE id = ?";
pstmt = conn.prepareStatement(deleteSql);
pstmt.setInt(1, 1);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 确保关闭资源
try {
if (pstmt != null) pstmt.close();
if (conn != null && !conn.isClosed()) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new DruidJdbcExample().CRUDOperations();
}
}
```
在这个例子中,我们创建了一个`DruidDataSource`实例,然后在每个操作的开始获取连接,在操作结束后确保关闭`PreparedStatement`和`Connection`。使用finally块可以确保资源总是得到正确关闭,即使发生异常也是如此。
阅读全文