码迷,mamicode.com
首页 > 数据库 > 详细

java web-----DAO设计模式(数据库访问)

时间:2016-07-02 21:31:14      阅读:492      评论:0      收藏:0      [点我收藏+]

标签:

一,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("数据库连接关闭失败");
            }
        }
    }
}
View Code

  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;
    }
    
    
}
View Code

  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;
}
View Code

  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;
    }

}
View Code

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

技术分享
package com.javaweb.dao;

public class DAOFactory
{
    public static UserDAO getUserDAOInstance()
    {
        return new UserDAOImpl();
    }
}
View Code

 

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

  代码示例:

技术分享
<%@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>
View Code

 

java web-----DAO设计模式(数据库访问)

标签:

原文地址:http://www.cnblogs.com/weiyikang/p/5636019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!