详细代码请参见 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接口。

 

package com.ljh.jasonnews.server.dao;

import java.sql.Connection;

public interface Dao {

	public Connection getConnection() throws DaoException;

}

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

 

package com.ljh.jasonnews.server.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class DaoBase implements Dao { @Override
public Connection getConnection() throws DaoException {
try {
//注册JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver"); //打开一个数据库连接
String URL = "jdbc:mysql://1.2.3.4:3306/filter_conf";
String USERNAME = "lujinhong";
String PASSWORD = "lujinhong"; Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
return conn; //return dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
throw new DaoException();
}
} protected void closeDbObject(ResultSet rs, Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

3、创建DaoException。

 package com.ljh.jasonnews.server.dao;

public class DaoException extends Exception{
private String message;
public DaoException(){}
public DaoException(String message){
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
} public String toString(){
return message;
} }

 

 

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

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

 

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

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

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

 

package com.ljh.jasonnews.server.dao.factory;

import com.ljh.jasonnews.server.dao.CategoryDao;
import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl; public class DaoFactory { public static CategoryDao getCategoryDao() {
return new CategoryDaoImpl();
}
}

5、创建Model类。

package com.ljh.jasonnews.server.model;

public class Category {

	public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getSequnce() {
return sequnce;
}
public void setSequnce(int sequnce) {
this.sequnce = sequnce;
}
public int getDeleted() {
return deleted;
}
public void setDeleted(int deleted) {
this.deleted = deleted;
}
private int cid;
private String title;
private int sequnce = 0;
private int deleted = 0;
}

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

 

package com.ljh.jasonnews.server.dao;

import java.util.List;

import com.ljh.jasonnews.server.model.Category;

public interface CategoryDao extends Dao{

	public List getCategoryList() throws DaoException;

}

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

 

package com.ljh.jasonnews.server.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import com.ljh.jasonnews.server.dao.CategoryDao;
import com.ljh.jasonnews.server.dao.DaoBase;
import com.ljh.jasonnews.server.dao.DaoException;
import com.ljh.jasonnews.server.model.Category; public class CategoryDaoImpl extends DaoBase implements CategoryDao { @Override
public List getCategoryList() throws DaoException{ String GET_CATEGORY_SQL = "SELECT * FROM T_CATEGORY"; List categoryList = new ArrayList(); Connection conn = null;
PreparedStatement pStatment =null;
ResultSet rs = null;
try{
conn = getConnection();
System.out.println("a");
pStatment = conn.prepareStatement(GET_CATEGORY_SQL);
System.out.println("b");
rs = pStatment.executeQuery();
System.out.println("c");
while(rs.next()){
Category category = new Category();
category.setCid(rs.getInt("cid"));
category.setTitle(rs.getString("title"));
category.setSequnce(rs.getInt("sequnce"));
category.setDeleted(rs.getInt("deleted"));
categoryList.add(category);
}
}catch(Exception e){
throw new DaoException("Erorr getting Categorys. " + e.getMessage());
}finally{
closeDbObject(rs, pStatment, conn);
} return categoryList; }
 

 

 

其它说明:

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

package com.ljh.jasonnews.server.dao.test;

import java.util.Iterator;
import java.util.List; import org.junit.Test; import com.ljh.jasonnews.server.dao.CategoryDao;
import com.ljh.jasonnews.server.dao.impl.CategoryDaoImpl;
import com.ljh.jasonnews.server.model.Category; public class CategoryDaoTest { @Test
public void test() throws Exception{
CategoryDao categoryDao = DaoFactory.getCategoryDao();
List categoryList = categoryDao.getCategoryList();
Iterator iterator = categoryList.iterator();
while(iterator.hasNext()){
Category category = iterator.next();
System.out.println(category.getCid()+" "+ category.getTitle()+" "+category.getSequnce()+" "+ category.getDeleted()+" ");
} } }

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,否则,在以下代码中会报错:

 

 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. theme- 自定义控件属性

    今天想要在一个控件中增加自己的一条属性,具体步骤如下 1.在frameworks/base/core/res/res/values/attr中注册属性 因为我们希望增加的属性是在AutoComplet ...

  2. GPU-Z:显卡体质、显卡各传感器实时状态的查看

    1. TechPowerUp GPU-Z:查看显卡体质 下载地址:Download TechPowerUp GPU-Z | techPowerUp 点击 bus interface 后的?进行显卡的体 ...

  3. Android 多线程断点续传同时下载多个大文件

    最近学习在Android环境中一些网络请求方面的知识,其中有一部分是关于网络下载方面的知识.在这里解析一下自己写的demo,总结一下自己所学的知识.下图为demo的效果图,仿照一些应用下载商城在Lis ...

  4. 关于后台接收参数为null的问题之ajax--contentType

    ajax方法中的参数: contentType:发送至服务器时内容的编码类型,一般默认:application/x-www-form-urlencoded(适应大多数的场合) dataType:预期服 ...

  5. 洛谷——V1772 巧妙填数

    描述 将1,2,\cdots,91,2,⋯,9共99个数分成三组,分别组成三个三位数,且使这三个三位数构成1:2:31:2:3的比例. 试求出所有满足条件的三个三位数.例如:三个三位数192,384, ...

  6. 解决iOS空指针数据的问题

    iOS开发中常常会遇到空指针的问题. 如从后台传回来的Json数据,程序中不做推断就直接赋值操作,非常有可能出现崩溃闪退. 为了解决空指针的问题,治标的方法就是遇到一个处理一个.这样业务代码里面就插了 ...

  7. html5 audio标签相关知识点总结

    1.audio指JS原生对象,假如用jquery获取到audio标签后,需要dom[0]转为原生JS对象 if(audio.paused){ //如果音频暂停,就播放 audio.play(); }e ...

  8. 洛谷 P2368 EXCEEDED WARNING B

    P2368 EXCEEDED WARNING B 题目背景 SGU 107 题目描述 求有多少个平方后末尾为987654321的n位数 输入输出格式 输入格式: 整数n 输出格式: 答案,即[b]“平 ...

  9. Dynamics CRM2016 Web API之Expand related entities &amp; $ref &amp; $count

    本篇介绍两个关于1:N关系中通过主实体取关联子实体的api,这两个api会常常被用到并且比原来的odata方式更加方便.之前假设我们要取主实体下全部的关联实体的记录都是通过Retrieve Multi ...

  10. sshfs 通过ssh 挂载远程目录

    安装:yum -y install sshfs 挂载远程 ssh 文件系统: sshfs -p 1234 root@192.168.1.218:/home/ /mnt/ sshfs -p SSH端口 ...