详细代码请参见 https://github.com/lujinhong/dao

一、前期准备

1、创建数据库

create database filter_conf;

2、创建表并插入数据

create table T_CATEGORY(cid Int, title varchar(256), sequnce int, deleted int);

insert into T_CATEGORY values(1,lujinhong,1,1);

3、准备pom.xml

我习惯使用maven作包管理,因此在pom.xml中加入以下内容:

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>5.1.36</version>

</dependency>

OK,开工写代码

 

二、java创建 

1、创建Dao接口。

 

  1. package com.ljh.jasonnews.server.dao;
  2.  
  3. import java.sql.Connection;
  4.  
  5. public interface Dao {
  6.  
  7. public Connection getConnection() throws DaoException;
  8.  
  9. }

2、创建BaseDao类,实现Dao接口,主要完成数据库的打开与关闭

 

  1. package com.ljh.jasonnews.server.dao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. public class DaoBase implements Dao {
  10.  
  11. @Override
  12. public Connection getConnection() throws DaoException {
  13. try {
  14. //注册JDBC驱动程序
  15. Class.forName("com.mysql.jdbc.Driver");
  16.  
  17. //打开一个数据库连接
  18. String URL = "jdbc:mysql://1.2.3.4:3306/filter_conf";
  19. String USERNAME = "lujinhong";
  20. String PASSWORD = "lujinhong";
  21.  
  22. Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
  23. return conn;
  24.  
  25. //return dataSource.getConnection();
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. throw new DaoException();
  29. }
  30. }
  31.  
  32. protected void closeDbObject(ResultSet rs, Statement stmt, Connection conn){
  33. if(rs != null){
  34. try {
  35. rs.close();
  36. } catch (SQLException e) {
  37. e.printStackTrace();
  38. }
  39. }
  40.  
  41. if(stmt != null){
  42. try {
  43. stmt.close();
  44. } catch (SQLException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48.  
  49. if(conn != null){
  50. try {
  51. conn.close();
  52. } catch (SQLException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  1. } 

3、创建DaoException。

 package com.ljh.jasonnews.server.dao;

  1. public class DaoException extends Exception{
  2. private String message;
  3. public DaoException(){}
  4. public DaoException(String message){
  5. this.message = message;
  6. }
  7. public String getMessage() {
  8. return message;
  9. }
  10. public void setMessage(String message) {
  11. this.message = message;
  12. }
  13.  
  14. public String toString(){
  15. return message;
  16. }
  17.  
  18. }

 

 

以上为jdbc DAO模式的基本步骤,主要用于获取连接及异常处理。

以下步骤对于每个表均要进行新增类(***Dao,***DaoImpl,model.***)以及在类中新增方法(DaoFactory)。

 

4、创建DaoFactory类,用于生产Dao对象。

对于较少的连接,可以在factory中每次直接new 一个***DaoImpl对象,如本例。

对于某些较多的连接,可能需要使用连接池等限制连接数量,说见本文最后面。

 

  1. package com.ljh.jasonnews.server.dao.factory;
  2.  
  3. import com.ljh.jasonnews.server.dao.CategoryDao;
  4. import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl;
  5.  
  6. public class DaoFactory {
  7.  
  8. public static CategoryDao getCategoryDao() {
  9. return new CategoryDaoImpl();
  10. }
  11. }

5、创建Model类。

  1. package com.ljh.jasonnews.server.model;
  2.  
  3. public class Category {
  4.  
  5. public int getCid() {
  6. return cid;
  7. }
  8. public void setCid(int cid) {
  9. this.cid = cid;
  10. }
  11. public String getTitle() {
  12. return title;
  13. }
  14. public void setTitle(String title) {
  15. this.title = title;
  16. }
  17. public int getSequnce() {
  18. return sequnce;
  19. }
  20. public void setSequnce(int sequnce) {
  21. this.sequnce = sequnce;
  22. }
  23. public int getDeleted() {
  24. return deleted;
  25. }
  26. public void setDeleted(int deleted) {
  27. this.deleted = deleted;
  28. }
  29. private int cid;
  30. private String title;
  31. private int sequnce = 0;
  32. private int deleted = 0;
  33. }

6、创建***Dao接口,继承Dao接口。

 

  1. package com.ljh.jasonnews.server.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.ljh.jasonnews.server.model.Category;
  6.  
  7. public interface CategoryDao extends Dao{
  8.  
  9. public List getCategoryList() throws DaoException;
  10.  
  11. }

7、创建***DaoImpl类,继承DaoBase类。

 

  1. package com.ljh.jasonnews.server.dao.impl;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import com.ljh.jasonnews.server.dao.CategoryDao;
  10. import com.ljh.jasonnews.server.dao.DaoBase;
  11. import com.ljh.jasonnews.server.dao.DaoException;
  12. import com.ljh.jasonnews.server.model.Category;
  13.  
  14. public class CategoryDaoImpl extends DaoBase implements CategoryDao {
  15.  
  16. @Override
  17. public List getCategoryList() throws DaoException{
  18.  
  19. String GET_CATEGORY_SQL = "SELECT * FROM T_CATEGORY";
  20.  
  21. List categoryList = new ArrayList();
  22.  
  23. Connection conn = null;
  24. PreparedStatement pStatment =null;
  25. ResultSet rs = null;
  26. try{
  27. conn = getConnection();
  28. System.out.println("a");
  29. pStatment = conn.prepareStatement(GET_CATEGORY_SQL);
  30. System.out.println("b");
  31. rs = pStatment.executeQuery();
  32. System.out.println("c");
  33. while(rs.next()){
  34. Category category = new Category();
  35. category.setCid(rs.getInt("cid"));
  36. category.setTitle(rs.getString("title"));
  37. category.setSequnce(rs.getInt("sequnce"));
  38. category.setDeleted(rs.getInt("deleted"));
  39. categoryList.add(category);
  40. }
  41. }catch(Exception e){
  42. throw new DaoException("Erorr getting Categorys. " + e.getMessage());
  43. }finally{
  44. closeDbObject(rs, pStatment, conn);
  45. }
  46.  
  47. return categoryList;
  48.  
  49. }
  50.  

  1.  

 

其它说明:

1、创建TestCase,测试数据库连接。

  1. package com.ljh.jasonnews.server.dao.test;
  2.  
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. import org.junit.Test;
  7.  
  8. import com.ljh.jasonnews.server.dao.CategoryDao;
  9. import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl;
  10. import com.ljh.jasonnews.server.model.Category;
  11.  
  12. public class CategoryDaoTest {
  13.  
  14. @Test
  15. public void test() throws Exception{
  16. CategoryDao categoryDao = DaoFactory.getCategoryDao();
  17. List categoryList = categoryDao.getCategoryList();
  18. Iterator iterator = categoryList.iterator();
  19. while(iterator.hasNext()){
  20. Category category = iterator.next();
  21. System.out.println(category.getCid()+" "+ category.getTitle()+" "+category.getSequnce()+" "+ category.getDeleted()+" ");
  22. }
  23.  
  24. }
  25.  
  26. }

2、在数据库中访问数据,最重要且最费时的操作经常是建立连接。按规则,设计良好的应用程序数据库连接应该始终是采用连接池的。

 

一般而言,使用连接池有以下三种方法:

l  Apache Commons DBCP

l  C3p0

l  Tomcat7中的Tomcat JDBCConnection Pool

    使用Tomcat的项目,建立直接使用TomcatJDBC Connection Pool。调用DataSource.getConnection()方法比较快,因为连接永远不会被关闭:关闭连接时,只要将连接返回池中即可。但是,JNDI查找比较慢,因此,被返回的DataSource经常会被缓存起来。

 

注:

(1)在调试中,未能使用连接池完成数据库连接,因此本示例中未使用连接池,关于连接池,可参考DataSourceCache.java,但关键是context.xml与web.xml中的配置。

(2)在需要调用context相关的应用中,不能直接使用junit进行测试,而必须创建一个jsp或者servlet,否则,在以下代码中会报错:

 

  1. Context envContext = (Context)context.lookup("java:/comp/env");

(3)作用连接池有JNDI及依赖注入2种方式,目前更推荐使用依赖注入。

 

 

之后再补充关于连接池以及缓存相关的代码。

 

 

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

jdbc之二:DAO模式 分类: B1_JAVA 2014-04-29 15:13 1536人阅读 评论(0) 收藏的更多相关文章

  1. 【solr基础教程之二】索引 分类: H4_SOLR/LUCENCE 2014-07-18 21:06 3331人阅读 评论(0) 收藏

    一.向Solr提交索引的方式 1.使用post.jar进行索引 (1)创建文档xml文件 <add> <doc> <field name="id"&g ...

  2. Find The Multiple 分类: 搜索 POJ 2015-08-09 15:19 3人阅读 评论(0) 收藏

    Find The Multiple Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 21851 Accepted: 8984 Sp ...

  3. 周赛-DZY Loves Chessboard 分类: 比赛 搜索 2015-08-08 15:48 4人阅读 评论(0) 收藏

    DZY Loves Chessboard time limit per test 1 second memory limit per test 256 megabytes input standard ...

  4. 欧拉通路-Play on Words 分类: POJ 图论 2015-08-06 19:13 4人阅读 评论(0) 收藏

    Play on Words Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 10620 Accepted: 3602 Descri ...

  5. Ultra-QuickSort 分类: POJ 排序 2015-08-03 15:39 2人阅读 评论(0) 收藏

    Ultra-QuickSort Time Limit: 7000MS   Memory Limit: 65536K Total Submissions: 48111   Accepted: 17549 ...

  6. Drainage Ditches 分类: POJ 图论 2015-07-29 15:01 7人阅读 评论(0) 收藏

    Drainage Ditches Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 62016 Accepted: 23808 De ...

  7. cf 61E. Enemy is weak 树状数组求逆序数(WA) 分类: Brush Mode 2014-10-19 15:16 104人阅读 评论(0) 收藏

    #include <iostream> #include <algorithm> #include <cstdio> #include <cstring> ...

  8. max_flow(Dinic) 分类: ACM TYPE 2014-09-02 15:42 94人阅读 评论(0) 收藏

    #include <cstdio> #include <iostream> #include <cstring> #include<queue> #in ...

  9. SQL 分组 加列 加自编号 自编号限定 分类: SQL Server 2014-11-25 15:41 283人阅读 评论(0) 收藏

    说明: (1)日期以年月形式显示:convert(varchar(7),字段名,120) , (2)加一列 (3)自编号: row_number() over(order by 字段名 desc) a ...

随机推荐

  1. dump var_dump print print_r的区别

    dump var_dump print print_r的区别 一.总结 用dump()来打印就对了 1.echo和print:不能打印复合型和资源型数据: 2.var_dump()和print_r() ...

  2. Sql延时

    IF EXISTS(SELECT * FROM sys.procedures WHERE name='usp_wait30s')BEGIN DROP PROC usp_wait30sENDgocrea ...

  3. alert警告框

    标签中写: <div class="alert alert-warning fade in"> <button class="close" d ...

  4. 用两个栈实现队列与用两个队列实现栈(Python实现)

    用两个栈实现队列: class QueueWithTwoStacks(object): def __init__(self): self._stack1 = [] self._stack2 = [] ...

  5. 【hdu 4333】Revolving Digits

    [链接]http://acm.hdu.edu.cn/showproblem.php?pid=4333 [题意] 就是给你一个数字,然后把最后一个数字放到最前面去,经过几次变换后又回到原数字,问在这些数 ...

  6. HDU 2068 RPG的错排(错排公式 + 具体解释)

    RPG的错排 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Sub ...

  7. 在安卓(手机)上运行 Ubuntu (Linux)

    在安卓(手机)上运行 Ubuntu (Linux) 由于x86 和 arm 是跨平台的,所使用的编译器自然也不同.如果要在电脑上编译安卓手机上的程序,则需在电脑端建立ARM交叉编译环境,这个过程是在耗 ...

  8. 全球可信并且唯一免费的HTTPS(SSL)证书颁发机构:StartSSL

    全球可信并且唯一免费的HTTPS(SSL)证书颁发机构:StartSSL http://blog.s135.com/startssl/ 购买权威机构的证书一年大概得七八千元,其实这是不值得的,所以一直 ...

  9. 移动开发js库Zepto.js使用中的一些注意点

    来自http://chaoskeh.com/blog/some-experience-of-using-zepto.html的参考. 前段时间完成了公司一个产品的 HTML5 触屏版,开发中使用了 Z ...

  10. Python 极简教程(四)变量与常量

    变量和常量 在 Python 中没有 常量 与 变量 之分.只有约定成俗的做法: 全大写字母的名称即为 常量: PI = 3.1415926 全小写字母的名称为 变量: name = 'nemo' 变 ...