JDBC连接数据库(续)

昨天写了jdbc打通数据库连接,今天闲来没事就完善了一下,这是一段MVC模式调用的代码

MVC编程模式:

MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建应用程序的模式:

  1. Model(模型)表示应用程序核心(比如数据库记录列表)。
  2. View(视图)显示数据(数据库记录)。
  3. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值