步骤
1.创建User类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
2.UserDao和UserImpl
mport com.sty.pojo.User;
import java.util.List;
public interface UserDao {
void addUser(User user);
void deleteUser(int id);
int updateUser(User user);
User queryUserByID(int id);
List<User> queryUser();
}
import com.sty.pojo.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.List;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
//为了Spring 注入
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//添加用户
public void addUser(User user) {
String sql = "insert into user(username,password) values (?,?)";
Object[] obj= new Object[]{
user.getUsername(),
user.getPassword()
};
jdbcTemplate.update(sql,obj);
}
//删除用户信息
public void deleteUser(int id) {
String sql ="delete from user where id=?";
jdbcTemplate.update(sql,id);
}
//修改用户信息
public int updateUser(User user) {
String sql ="update user set username=?,password=? where id=?";
Object[] obj =new Object[]{
user.getUsername(),
user.getPassword(),
user.getId()
};
int num = jdbcTemplate.update(sql, obj);
return num;
}
//查询用户
public User queryUserByID(int id) {
String sql="select * from day10.user where id=?";
RowMapper<User> RowMapper = new BeanPropertyRowMapper<User>(User.class);
User user = jdbcTemplate.queryForObject(sql, RowMapper,id);
return user;
}
public List<User> queryUser() {
String sql = "select * from user";
RowMapper<User> mapper = new BeanPropertyRowMapper<User>(User.class);
List<User> list = jdbcTemplate.query(sql,mapper);
return list;