DbUtils简单封装JDBC

版权声明:转载请注明出处:http://blog.csdn.net/u010143291 https://blog.csdn.net/u010143291/article/details/51701384

DBUtils封装JDBC框架

JDBC的一些语句进行封装,对于用户的使用提供了很大的方便,因此,有许多的商家都对JDBC进行了封装,比较出名的就有以下三家。

1.Hibernate 全自动的封装,不需要写SQL语句;

2.Itatis 半自动的框架,需要写SQL语句;

3.DBUtils简单的封装框架。

其中commons-dbutilsApache公司的开源软件,对JDBC进行了简单的封装。

使用到的API

QueryRunner类,

该类是一个线程安全的类,是DBUtils框架的核心类,它是一个构造器,可以通过new一个实例,将DataSource(即连接池)作为参数传进去,这样在后面调用方法时就不用再传递Connection了,QueryRunner会自动地在连接池中获取一个Connection而且Connection也会被自动的关闭,不用用户显式关闭。

常用的方法:

查询的重载方法:

<T> T  query(Connection conn, String sql, ResultSetHandler<T> rsh)

<T> T  query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)

<T> T  query(String sql, ResultSetHandler<T> rsh)

<T> T  query(String sql, ResultSetHandler<T> rsh, Object... params)

======================================================================

增删改的重载方法:

int  update(Connection conn, String sql)

int  update(Connection conn, String sql, Object... params)

int  update(Connection conn, String sql, Object param)

int  update(String sql)

int  update(String sql, Object... params)

int  update(String sql, Object param)

多学一招:

在使用DbUtilsQueryRunner类调用相关方法的时候,PreparedStatement会自动的关闭,不需要用户去显式关闭。

增删改相关方法的使用举例:

在构建QueryRunner时没有传入DataSource的情况

插入:

String sql = "insert into user(username,tel) values(?,?)";

Object[] params = {"marry","5555555"};

Connection conn = JdbcUtil.getConnection();

QueryRunner runner = new QueryRunner();

runner.update(conn,sql,params);

 修改

String sql = "update user set tel='23456' where id=?";

Object param = 7;

QueryRunner runner = new QueryRunner();

runner.update(conn,sql,param);

 删除

String sql = "delete from user where id=?";

Object param = 7;

Connection conn = JdbcUtil.getConnection();

QueryRunner runner = new QueryRunner();

runner.update(conn, sql, param);

使用DataSource的情况:

在构造QueryRunner时传入DataSource,那么在调用相关的方法时就不用再传入Connection了,也不用关闭Connection了,因为QueryRunner已经自动关闭连接了。

举例:

//使用DataSource的情况

String sql = "insert into user(username,tel) values(?,?)";

Object[] params = {"万物复苏","10987654321"};

//传入一个连接池,获取一个构造器

QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

runner.update(sql, params);

 查找( query )的相关方法使用:

使用query()方法,返回的是一个封装好的Bean对象,要传入对应的Class,所以,自动的封装的可以很方便地给用户使用。

并且调用query方法也不用用户显式地关闭ResultSet,框架已经自动关闭了。

举例:

//查找的情况

String sql = "select * from user where id=?";

Object param = 2;

QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());

User user = (User)runner.query(sql, new BeanHandler(User.class), param);

System.out.println(user.getUsername()+","+user.getTel());


DbUtils体验:

1.导入相关的jar包:(使用dbcp连接池)
DbUtils相关包1个 +dbcpjar包(2个)+ mysql连接驱动包(1个)
commons-dbcp-1.2.2.jar
commons-pool.jar
commons-dbutils-1.2.jar
mysql-connector-java-5.0.8-bin.jar


2.创建表:

drop database if exists day05;
	create database if not exists day05;
	alter database day05 character set utf8 collate utf8_general_ci;
	use day05;


	drop table if exists user;
	create table if not exists user(
	id int primary key,
	name varchar(10),
	password varchar(10),
	email varchar(20),
	birthday date);
新建JavaBean/User类(封装查询到的数据)
package cn.lsh.domain;


import java.util.Date;


public class User {
	private int id;
	private String name;
	private String password;
	private String email;
	private Date birthday;
	
	
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(int id, String name, String password, String email,
			Date birthday) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
		this.email = email;
		this.birthday = birthday;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

3.创建JdbcUtils工具类:
package cn.lsh.utils;


import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


import javax.sql.DataSource;


import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;


public class JdbcUtils {
	private static DataSource ds;
	static{
		try {
			Properties pro = new Properties();
			InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
			pro.load(in);
			BasicDataSourceFactory bs = new BasicDataSourceFactory();
			ds = bs.createDataSource(pro);
			} catch (Exception e) {
			throw new ExceptionInInitializerError();
		}
	}
	
	public static DataSource getDataSource(){
		return ds;
	}
}

4.dbcpconfig.properties配置文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day05
username=root

password=root


新建JdbcTest:

package cn.lsh.jdbc;

import java.util.Date;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.lsh.domain.User;
import cn.lsh.utils.JdbcUtils;

public class TestDemo1 {
/*
	id int primary key,
	name varchar(10),
	password varchar(10),
	email varchar(20),
	birthday date);
	*/
	public static void main(String[] args) throws Exception {
		//insert();
		//update();
		//delete();
		select();
	}
	//添加数据
	public static void insert() throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "insert into user(id,name,password,email,birthday) values(?,?,?,?,?)";
		Object [] params = {1,"aaa","123","aaa@sina.com",new Date()};
		runner.update(sql, params);
	}
	
	//更新数据
	public static void update() throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "update user set email=? where id=?";
		Object [] params = {"bbb@qq.com",1};
		runner.update(sql, params);
	}
	
	//删除数据
	public static void delete() throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "delete from user where id=?";
		runner.update(sql,1);
	}
	
	//查找所有数据
	public static void select() throws Exception{
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from user where id=?";
		//调用query方法把查询到的数据封装成user对象
		User user = (User) runner.query(sql, 1, new BeanHandler(User.class));
		//输出
		System.out.println(user.getName()+","+user.getEmail()+","+user.getBirthday());//aaa,aaa@sina.com,2016-06-17
		
	}
	
}

5.测试:
查询数据库结果为:

//添加
mysql> select * from user;
+----+------+----------+--------------+------------+
| id | name | password | email        | birthday   |
+----+------+----------+--------------+------------+
|  1 | aaa  | 123      | aaa@sina.com | 2016-06-17 |
+----+------+----------+--------------+------------+
1 row in set (0.00 sec)


//更新
mysql> select * from user;
+----+------+----------+------------+------------+
| id | name | password | email      | birthday   |
+----+------+----------+------------+------------+
|  1 | aaa  | 123      | bbb@qq.com | 2016-06-17 |
+----+------+----------+------------+------------+
1 row in set (0.00 sec)


//删除(查询为空)
mysql> select * from user;
Empty set (0.00 sec)


查询用户数据
控制台输出结果为:aaa,aaa@sina.com,2016-06-17


阅读更多
想对作者说点什么? 我来说一句
相关热词

没有更多推荐了,返回首页