2) 编写数据库帮助类DBHelper,该类实现DBConfig接口;然后在该类中创建Connection、Statement和ResultSet类型的引用;接着编写静态的getConnection()方法,该方法返回Connection类型的对象;静态openStatement()方法,该方法返回值为Statement类型的对象;静态update(String sql)方法,该方法返回值为int型,用于完成数据的增(insert)、删(delete)、改(update);query(String sql)方法,该方法返回值为ResultSet类型的对象,用于完成数据的查询(select);静态Close()方法,无返回值,用于释放各种资源。
时间: 2023-12-10 21:36:59 浏览: 30
下面是DBHelper类的代码实现:
```java
import java.sql.*;
public class DBHelper implements DBConfig {
private Connection conn;
private Statement stmt;
private ResultSet rs;
public DBHelper() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
return conn;
}
public Statement openStatement() throws SQLException {
stmt = getConnection().createStatement();
return stmt;
}
public int update(String sql) {
int result = 0;
try {
stmt = openStatement();
result = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
return result;
}
public ResultSet query(String sql) {
try {
stmt = openStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void close() {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
上面的代码中,DBHelper类实现了DBConfig接口,该接口包括了数据库连接的相关配置信息。在DBHelper类中,定义了Connection、Statement和ResultSet类型的引用,用于操作数据库。getConnection()方法用于获取数据库连接对象,openStatement()方法用于打开Statement对象,update(String sql)方法用于执行数据的增、删、改操作,query(String sql)方法用于执行数据的查询操作,close()方法用于释放各种资源。
相关推荐
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)