jdbc增删改查工具类
时间: 2023-05-23 21:03:08 浏览: 72
下面是一个简单的 JDBC 工具类实现增删改查操作:
```java
import java.sql.*;
public class JdbcUtils {
/**
* 获取数据库连接
*/
public static Connection getConnection(String url, String username, String password) throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* 关闭数据库连接
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行查询操作
*/
public static void executeQuery(Connection conn, String sql) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
// 处理查询结果
}
} finally {
close(conn, stmt, rs);
}
}
/**
* 执行更新操作
*/
public static void executeUpdate(Connection conn, String sql) throws SQLException {
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} finally {
close(conn, stmt, null);
}
}
}
```
使用时可以这样调用:
```java
Connection conn = JdbcUtils.getConnection(url, username, password);
JdbcUtils.executeQuery(conn, "SELECT * FROM users WHERE age > 18");
JdbcUtils.executeUpdate(conn, "UPDATE users SET age = 20 WHERE name = '张三'");
JdbcUtils.close(conn, null, null);
```
注意:这只是一个简单的实现,实际开发中可能需要更复杂的功能和更严格的安全性控制。