DAO设计

一,DAO设计模式用于 j2ee 的数据层访问,包括五部分,

数据库连接类(包含数据库的连接与关闭操作的一个类),

VO类(私有变量与数据库表格对应,接收数据库中表格各字段内容),

DAO接口类(包含数据库的各项操作,增,删,改,查函数的定义),

DAO实现类(具体实现DAO接口中定义的数据库操作函数),

DAO工厂类(提供一个返回值为DAO接口类型的静态方法,获得DAO实现的实例)



以一个mysql数据库中简单的用户表(userid 自增长,username,password)为例的DAO各个模块:

  1.数据库连接类:


复制代码
package com.javaweb.dao;

import java.sql.*;

public class DBConnection
{
    private final String DBDRIVER = "com.mysql.jdbc.Driver";
    private final String DBURL = "jdbc:mysql://localhost:3306/javaweb";
    private final String USER = "root";
    private final String PASSWORD = "root";
    private Connection conn=null;

    public DBConnection()
    {
        try
        {
            Class.forName(DBDRIVER);
            this.conn = DriverManager.getConnection(DBURL,USER,PASSWORD);
        } catch (ClassNotFoundException | SQLException e)
        {
            // TODO Auto-generated catch block
            System.out.println("加载驱动失败");
        }

    }

    public Connection getConnection()
    {
        return this.conn;
    }

    public void close()
    {
        if(this.conn!=null)
        {
            try
            {
                this.conn.close();
            } catch (SQLException e)
            {
                // TODO Auto-generated catch block
                System.out.println("数据库连接关闭失败");
            }
        }
    }
}
复制代码
  2.VO类:


复制代码
package com.javaweb.dao;

public class User
{
    private int userid;
    private String username;
    private String password;

    public User()
    {
        // TODO Auto-generated constructor stub
    }

    public int getUserid()
    {
        return userid;
    }
    public void setUserid(int userid)
    {
        this.userid = userid;
    }
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }


}
复制代码
  3.DAO接口:


复制代码
package com.javaweb.dao;
import java.util.List;

public interface UserDAO
{
    public void insert(User user) throws Exception;
    public void delete(int userid) throws Exception;
    public void update(User user) throws Exception;
    public User querryById(int userid) throws Exception;
    public List querryALL() throws Exception;
}
复制代码
  4.DAO具体实现:


复制代码
package com.javaweb.dao;

import java.util.ArrayList;
import java.util.List;
import java.sql.*;

public class UserDAOImpl implements UserDAO
{

    @Override
    public void insert(User user) throws Exception
    {
        // TODO Auto-generated method stub
        DBConnection con = null;
        PreparedStatement pstm = null;
        String sql = "insert into user(username,password) values(?,?)";

        try
        {
            con = new DBConnection();
            pstm = con.getConnection().prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            pstm.executeUpdate();
            if (pstm != null)
            {
                pstm.close();
            }
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("插入数据操作异常");
        } finally
        {
            if (con != null)
            {
                con.close();
            }
        }
    }

    @Override
    public void delete(int userid) throws Exception
    {
        // TODO Auto-generated method stub
        DBConnection con = null;
        PreparedStatement pstm = null;
        String sql = "delete from user where userid=?";

        try
        {
            con = new DBConnection();
            pstm = con.getConnection().prepareStatement(sql);
            pstm.setInt(1, userid);
            pstm.executeUpdate();
            if (pstm != null)
            {
                pstm.close();
            }
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("删除数据操作异常");
        } finally
        {
            if (con != null)
            {
                con.close();
            }
        }
    }

    @Override
    public void update(User user) throws Exception
    {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub
        DBConnection con = null;
        PreparedStatement pstm = null;
        String sql = "update user set username=?,password=? where userid=?";

        try
        {
            con = new DBConnection();
            pstm = con.getConnection().prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            pstm.setInt(3, user.getUserid());
            pstm.executeUpdate();
            if (pstm != null)
            {
                pstm.close();
            }
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("更新数据操作异常,sql:"+sql);
        } finally
        {
            if (con != null)
            {
                con.close();
            }
        }
    }

    @Override
    public User querryById(int userid) throws Exception
    {
        // TODO Auto-generated method stub
        DBConnection con = null;
        PreparedStatement pstm = null;
        ResultSet rs=null;
        User user=null;
        String sql = "select * from user where userid=?";

        try
        {
            //获取连接
            con = new DBConnection();
            //预处理语句
            pstm = con.getConnection().prepareStatement(sql);
            //设置参数
            pstm.setInt(1, userid);
            //执行查询
            rs = pstm.executeQuery();
            //获取结果
            while(rs.next())
            {
                user = new User();
                user.setUserid(rs.getInt(1));
                user.setUsername(rs.getString(2));
                user.setPassword(rs.getString(3));
            }
            if (pstm != null)
            {
                pstm.close();
            }
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("查询数据操作异常   sql:"+sql);
        } finally
        {
            if (con != null)
            {
                con.close();
            }
        }
        return user;
    }

    @Override
    public List<User> querryALL() throws Exception
    {
        // TODO Auto-generated method stub
        DBConnection con = null;
        PreparedStatement pstm = null;
        ResultSet rs=null;
        List<User> lsu=new ArrayList<User>();
        String sql = "select * from user";

        try
        {
            //获取连接
            con = new DBConnection();
            //预处理语句
            pstm = con.getConnection().prepareStatement(sql);
            //执行查询,返回结果rs
            rs = pstm.executeQuery();
            //获取结果
            while(rs.next())
            {
                User user = new User();
                user.setUserid(rs.getInt(1));
                user.setUsername(rs.getString(2));
                user.setPassword(rs.getString(3));
                lsu.add(user);
            }
            if (pstm != null)
            {
                pstm.close();
            }
        } catch (Exception e)
        {
            // TODO Auto-generated catch block
            System.out.println("查询数据操作异常");
        } finally
        {
            if (con != null)
            {
                con.close();
            }
        }
        return lsu;
    }

}
复制代码
  5.DAO工厂(有效避免由于DAO实现改变导致的大量代码修改)


复制代码
package com.javaweb.dao;

public class DAOFactory
{
    public static UserDAO getUserDAOInstance()
    {
        return new UserDAOImpl();
    }
}
复制代码


二,通过jsp调用相关函数即可进行数据库操作,省去了大量重复代码。

  代码示例:

按 Ctrl+C 复制代码

<%@page import="com.javaweb.dao.*"%>
<%@page import="org.eclipse.jdt.internal.compiler.apt.model.Factory"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <%
        UserDAO userDAO = DAOFactory.getUserDAOInstance();
        User user=new User();
        user.setUsername("lu");
        user.setPassword("123");
        userDAO.insert(user);
    %>
</body>
</html>
按 Ctrl+C 复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值