同学录的JDBCUtils怎么写
时间: 2024-08-13 11:06:09 浏览: 58
`JDBCUtils`是一个简化Java数据库操作的工具类,通常用于封装JDBC(Java Database Connectivity)的基本操作,如连接数据库、执行SQL语句和处理结果集等。以下是一个基本的`JDBCUtils`示例,使用了`java.sql.Connection`, `java.sql.Statement`和`java.sql.ResultSet`:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCUtils {
// 初始化数据库连接池
private static Connection getConnection(String url, String username, String password) {
try {
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new RuntimeException("Failed to connect to database", e);
}
}
// 执行SQL查询
public static ResultSet query(String sql, Object... params) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection(DB_URL, DB_USER, DB_PASSWORD);
pstmt = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
}
rs = pstmt.executeQuery();
return rs;
} catch (Exception e) {
log.error("Error executing SQL: " + sql, e);
return null;
} finally {
closeQuietly(conn, pstmt, rs);
}
}
// 关闭资源
private static void closeQuietly(Object... objects) {
for (Object obj : objects) {
if (obj != null) {
try {
if (obj instanceof AutoCloseable) {
((AutoCloseable) obj).close();
}
} catch (Exception ignore) {
// Ignore exceptions during cleanup
}
}
}
}
// 其他方法可根据需要添加,例如存储过程调用、更新操作等
}
```
阅读全文