整体结构




model / entity
public class Player {
private Integer id;
private String name;
private String sex;
private Integer age;
private String address;
private String hobby;
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
dao
public class DBUtil {
public static Connection getConnection() {
Connection con = null;
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8";
String user = "root";
String password = "";
Class.forName(driver);
if(null == con) {
con = DriverManager.getConnection(url, user, password);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
}
service
public class PlayerService {
public int insertPlayer(Player player){
int ret = 0;
try {
Connection con = DBUtil.getConnection();
String sql = "insert into player values(null,?,?,?,?,?)";
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1,player.getName());
stm.setString(2,player.getSex());
stm.setInt(3,player.getAge());
stm.setString(4,player.getAddress());
stm.setString(5,player.getHobby());
ret = stm.executeUpdate();
stm.close();
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return ret;
}
public int deletePlayer(int id){
int ret = 0;
try {
Connection con = DBUtil.getConnection();
String sql = "delete from player where PlayerID = ?";
PreparedStatement stm = con.prepareStatement(sql);
stm.setInt(1,id);
ret = stm.executeUpdate();
stm.close();
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return ret;
}
public int updatePlayer(Player player){
int ret = 0;
try {
Connection con = DBUtil.getConnection();
String sql = "update player set Name=?,Sex=?,Age=?,Address=?,Hobby=? where PlayerID=?";
PreparedStatement stm = con.prepareStatement(sql);
stm.setString(1

本文介绍了使用Java编写的Player类,包括DAO、Service、Controller和Servlet,展示了如何通过DBUtil连接数据库进行增删改查操作,并在JSP页面展示数据。涵盖了数据库操作、HTTP请求处理和前端显示。
最低0.47元/天 解锁文章
3477

被折叠的 条评论
为什么被折叠?



