import java.sql.*;
/**课题:封装数据库的增删改查的工具类的实现。
*
* 假设相关数据库的表结构如下:
* 表名:user
* 列名及属性:id(int 自增),name(varchar(20)),tele(char(12)),birthday(date)
* @author shy2850
*/
public class UserDAO {
Connection conn;
public UserDAO(Connection conn) {
this.conn = conn;
}
public int save(User user) throws SQLException {
String sql = "insert into user values(0,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setString(2, user.getTele());
pstmt.setDate(3, user.getBirthday());
int n = pstmt.executeUpdate();
pstmt.close();
return n;
}
public int delete(User user) throws SQLException{
String sql = "delete from user where id = "+user.getId();
Statement stmt = conn.createStatement();
int n = stmt.executeUpdate(sql);
stmt.close();
return n;
}
public int update(User user) throws SQLException{
String sql = "update user set name=?, tele=?, birthday=? where id = "+user.getId();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(2, user.getName());
pstmt.setString(3, user.getTele());
pstmt.setDate(4, user.getBirthday());
int n = pstmt.executeUpdate(sql);
pstmt.close();
return n;
}
public User getUser(Integer id) throws SQLException{
String sql = "select * from user where id = " + id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
User user = getUserFromResultSet(rs);
rs.close();
stmt.close();
return user;
}
static User getUserFromResultSet(ResultSet rs) throws SQLException{
Integer id = rs.getInt("id");
String name= rs.getString("name");
String tele= rs.getString("tele");
Date birthday = rs.getDate("birthday");
return new User(id, name, tele, birthday);
}
}
/**
* 构建数据库表的java类映射
*/
class User{
private Integer id;
private String name;
private String tele;
private Date birthday;
public User() {
}
public User(Integer id, String name, String tele, Date birthday) {
super();
this.id = id;
this.name = name;
this.tele = tele;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTele() {
return tele;
}
public void setTele(String tele) {
this.tele = tele;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}