昨天写了jdbc打通数据库连接,今天闲来没事就完善了一下,这是一段MVC模式调用的代码
MVC编程模式:
MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建应用程序的模式:
- Model(模型)表示应用程序核心(比如数据库记录列表)。
- View(视图)显示数据(数据库记录)。
Controller(控制器)处理输入(写入数据库记录)。
MVC是一个框架模式,它强制性的使应用程序的输入、处理和输出分开。使用MVC应用程序被分成三个核心部件:模型、视图、控制器。
好了,废话不多说,直接上代码。
Model类:
public class Info {
private Integer id;
private String name;
private String sex;
private String tel;
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;
}
......//省略若干代码
}
Dao类:
public class Infodao {
public void addInfo(Info i) throws Exception{
Connection conn=DbUtil.getconConnection();
String sql =""+
"insert into student"+
"(id,name,sex,tel)"+
"values(?,?,?,?)";
PreparedStatement ptmt = conn.prepareStatement(sql);
ptmt.setInt(1, i.getId());
ptmt.setString(2, i.getName());
ptmt.setString(3, i.getSex());
ptmt.setString(4, i.getTel());
ptmt.execute();
}
public void updateInfo(Info i) throws SQLException{
Connection conn=DbUtil.getconConnection();
String sql =""+
"update student "+
"set name=?,sex=?,tel=? "+
"where id=? ";
PreparedStatement ptmt = conn.prepareStatement(sql);
ptmt.setString(1, i.getName());
ptmt.setString(2, i.getSex());
ptmt.setString(3, i.getTel());
ptmt.setInt(4, i.getId());
ptmt.execute();
}
public void delInfo(Integer id) throws SQLException{
Connection conn=DbUtil.getconConnection();
String sql =""+
"delete from student "+
"where id=? ";
PreparedStatement ptmt = conn.prepareStatement(sql);
ptmt.setInt(1, id);
ptmt.execute();
}
...//省略若干代码
}
Controller(控制层)
public class InfoAction {
public void add(Info info) throws Exception{
Infodao dao=new Infodao();
dao.addInfo(info);
}
public List<Info> query(List<Map<String, Object>> params) throws Exception{
Infodao dao=new Infodao();
return dao.query(params);
}
...//省略若干代码
}
view层由于时间关系,只写了最简单的控制台方式操作,在这里就不展示了。
项目已托管至Github,https://github.com/Rightpr0/JdbcCon