java中基于jdbc的dbhelper辅助类写法
时间: 2023-12-16 18:03:10 浏览: 117
以下是一个基于 JDBC 的 DBHelper 辅助类的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBHelper {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
public DBHelper() {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql, Object... params) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
return rs;
}
public int executeUpdate(String sql, Object... params) throws SQLException {
ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
return ps.executeUpdate();
}
public void close() {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
这个 DBHelper 类包含了连接数据库、执行查询和更新操作、关闭数据库连接等常用方法。使用时,只需实例化 DBHelper 类,然后调用其中的方法即可。例如:
```java
DBHelper dbHelper = new DBHelper();
try {
ResultSet rs = dbHelper.executeQuery("SELECT * FROM table_name WHERE column_name = ?", "value");
while (rs.next()) {
// 处理查询结果
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbHelper.close();
}
```
阅读全文