basedao代码
时间: 2023-07-03 22:22:19 浏览: 91
BaseDao 是一个基础的 DAO(Data Access Object)类,通常用于操作数据库。这里是一个示例代码:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class BaseDao<T> {
protected Connection connection;
public BaseDao(Connection connection) {
this.connection = connection;
}
protected abstract T build(ResultSet resultSet) throws SQLException;
protected abstract String getTableName();
public T findById(int id) throws SQLException {
String selectSql = "SELECT * FROM " + getTableName() + " WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(selectSql);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return build(resultSet);
}
return null;
}
public void deleteById(int id) throws SQLException {
String deleteSql = "DELETE FROM " + getTableName() + " WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteSql);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
public void save(T object) throws SQLException {
String insertSql = "INSERT INTO " + getTableName() + " VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertSql);
// set values to preparedStatement
preparedStatement.executeUpdate();
}
public void update(T object) throws SQLException {
String updateSql = "UPDATE " + getTableName() + " SET column1 = ?, column2 = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(updateSql);
// set values to preparedStatement
preparedStatement.executeUpdate();
}
}
```
这个类中提供了一些基本的 CRUD(Create,Read,Update,Delete)方法,可以用于操作数据库表中的数据。具体的实现需要子类来完成,因为不同的数据表可能有不同的字段和数据类型。通常情况下,我们会为每个数据表定义一个 DAO 类,继承 BaseDao 类,然后在子类中实现 build() 和 getTableName() 方法。这样就可以使用这个 DAO 类来操作数据库表了。
阅读全文