package dao.specification; import dao.userAbstractDAO; import entities.Users; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static util.SQLDatabaseConnection.getConnection; import static util.SQLDatabaseConnection.close; public class userDAO implements userAbstractDAO { private Connection connection = null; private PreparedStatement preparedStatement = null; private ResultSet resultSet = null; //@TODO UserDAO 插入功能 @Override public int insert(Users users) { return 0; } @Override public int delete(@NotNull Users users) { int flag; try { connection = getConnection(); String delete_sql = "delete from Users where id=?"; preparedStatement = connection.prepareStatement(delete_sql); preparedStatement.setLong(1, users.getId()); flag = preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { close(connection, preparedStatement, resultSet); } return flag; } @Override public int update(@NotNull Users users) { int flag = 0; try { connection = getConnection(); String update_sql = "update Users " + "set name = ?, phoneNumber = ?, address = ? " + "where id = ?"; preparedStatement = connection.prepareStatement(update_sql); preparedStatement.setString(1,users.getName()); preparedStatement.setString(2,users.getPhoneNumber()); preparedStatement.setString(3,users.getAddress()); preparedStatement.setLong(4,users.getId()); } catch (SQLException e) { throw new RuntimeException(e); } return flag; } //查询所有用户 @Override public List search(Users users) { List list = new ArrayList<>(); try { connection = getConnection(); String selectAll_sql = "select * from Users"; preparedStatement = connection.prepareStatement(selectAll_sql); preparedStatement.executeQuery(); while (resultSet.next()) { users.setName(resultSet.getString("name")); users.setPhoneNumber(resultSet.getString("phoneNumber")); users.setAddress(resultSet.getString("address")); list.add(users); } } catch (SQLException e) { throw new RuntimeException(e); } finally { close(connection, preparedStatement, resultSet); } return list; } //用ID查询用户 @Override public Users searchUsersByID(Long id) { Users user = null; String selectID_sql = "select * from Users where id = ?"; try { connection = getConnection(); preparedStatement = connection.prepareStatement(selectID_sql); preparedStatement.setLong(1, id); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { user = new Users(); user.setId(resultSet.getLong("id")); user.setName(resultSet.getString("name")); user.setPhoneNumber(resultSet.getString("phoneNumber")); user.setAddress(resultSet.getString("address")); } } catch (SQLException e) { throw new RuntimeException(e); } finally { close(connection, preparedStatement, resultSet); } return user; } }