DataSource--DBCP--C3P0--DBUtils
一.DataSource 接口(javax.sql)
1.连接池:
由于与数据库连接的创建和销毁非常占用资源,因此提出了连接池技术,用于提升java程序操作数据库的性能;连接池是创建和管理一个连接的缓冲池的技术,这些连接准备好被任何需要它们的线程使用。
2.介绍:DataSource是java提供的一个接口,规范着所有的想写连接池的人需要做的事情;具体的连接池都需要实现该接口;程序员可以面向Datasource操作具体的连接池对象;
3.定义:public interface DataSource extends CommonDataSource, Wrapper
4.常用方法:只有一个getConnection()
Connection getConnection() throws SQLException{}: Attempts to establish a connection with the data source that this
DataSource object represents.
Connection getConnection(String username,String password) throws SQLException{}:
5.具体的连接池实现技术主要有两类:DBCP和C3P0
二.DBCP--(DataBase Connection Pool)
1.介绍:
数据库连接池,是java数据库连接池的一种,由Apache开发,通过数据库连接池,可以让程序自动管理数据库连接的创建。
2.使用步骤:
1):下载并解压zip;(DBCP有两个zip文件)
2):复制核心的jar包到工程中;(commons-dbcp-1.4.jar, commons-pool-1.5.6.jar)
3):添加到本地;
4):复制配置文件到src目录下;并修改配置文件的信息;(该配置文件的名称和位置可以任意)
5):使用核心类;
3.核心类介绍:BasicDataSourceFactory
定义:public class BasicDataSourceFactory extends Object implements ObjectFactory
构造方法:只有一个空参构造
public BasicDataSourceFactory()
常用方法:
public static DataSource createDataSource(Properties properties) throws Exception{}:
注意参数为Properties类的实例化对象,返回值为DataSource;
4.自定义DBCP工具类:配置文件("dbcp.properties")需放在工程根目录下;
1 //需要首先导入包:mysql-connector-java-5.1.39-bin.jar(mysql驱动),commons-dbcp-1.4.jar,commons-pool-1.5.6.jar
2 import java.io.FileInputStream;
3 import java.sql.Connection;
4 import java.sql.SQLException;
5 import java.util.Properties;
6 import javax.sql.DataSource;
7 import org.apache.commons.dbcp.BasicDataSourceFactory;
8
9 public class MyDBCPUtils {
10 private static DataSource ds = null;
11 //使用静态代码块技术初始化ds对象(成员变量)
12 static {
13 // 获取DataSource
14 try {
15 FileInputStream in = new FileInputStream("dbcp.properties");
16 Properties p = new Properties();
17 p.load(in);
18 ds = BasicDataSourceFactory.createDataSource(p);//面向DBCP核心类,调用createDataSource()方法,返回DataSource
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 }
23 // 获取Connection
24 public static Connection getConnection() {
25 Connection c = null;
26 try {
27 c = ds.getConnection();
28 } catch (SQLException e) {
29 e.printStackTrace();
30 }
31 return c;
32 }
33 }
三.C3P0
1.介绍:
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate,Spring等。c3p0与dbcp区别:c3p0有自动回收空闲连接功能,dbcp做不到.
2.使用步骤:
1):下载并解压zip;
2):复制核心jar包到工程中即可:c3p0-0.9.1.2.jar;
3):添加到本地;
4):复制配置文件必须到src目录下,且配置文件的名称(c3p0-config.xml)不能改变;
5):直接创建ComboPooledDataSource核心类对象即可使用;
3.核心类 ComboPooledDataSource 类(com.mchange.v2.c3p0)
定义:public final class ComboPooledDataSource extends com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
implements PooledDataSource, java.io.Serializable, javax.naming.Referenceable
public interface PooledDataSource extends javax.sql.DataSource
ComboPooledDataSource类实现了PooledDataSource接口,该接口继承了DataSource接口;
构造方法:
public ComboPooledDataSource()
配置文件选项(补充):
4.自定义C3P0工具类:导入包:mysql-connector-java-5.1.39-bin.jar,c3p0-0.9.1.2.jar
1 /*配置文件必须到src目录下,且配置文件的名称(c3p0-config.xml)不能改变,程序中不会出现,但是会自动读取.
2 如果报超时错误,有可能是1.包没导入/2.文件没找到/3.数据库服务未开启*/
3
4 import java.sql.Connection;
5 import javax.sql.DataSource;
6 import com.mchange.v2.c3p0.ComboPooledDataSource;
7
8 public class MyC3P0Utils {
9 // 定义DataSource
10 private static DataSource ds = new ComboPooledDataSource(); // 多态,子类实例赋值给父类的父类
11
12 // 获取Connection
13 public static Connection getConnection() throws Exception {
14 Connection c = ds.getConnection();
15 return c;
16 }
17 // 返回连接池对象
18 public static DataSource getDataSource() {
19 return ds;
20 }
21 }
22
四.DBUtils--工具类,commons-dbutils-1.6.jar
1.概述:Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能。
2.使用步骤:
1):下载并解压zip;
2):复制核心jar包到工程中即可:commons-dbutils-1.6.jar;
3):添加到本地;
4):直接创建核心类对象即可使用;
3.核心类3个:
1):QueryRunner,用于封装sql执行对象;
2):ResultSetHandler用于封装ResultSet;
3):DButils, 用于事务的控制;
4.QueryRunner
定义:public class QueryRunner extends AbstractQueryRunner
构造方法:
public QueryRunner()
public QueryRunner(DataSource ds)
常用方法:
public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params)throws SQLException{}:
public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)throws SQLException{}:
public int update(Connection conn, String sql, Object... params)throws SQLException{}:Execute an SQL INSERT, UPDATE, or DELETE query.返回值为数据表里受影响的行数(int类型);
public int update(String sql, Object... params)throws SQLException{}:Executes the given INSERT, UPDATE, or DELETE SQL statement. The Connection is retrieved from the DataSource set in the constructor. This Connection must be in auto-commit mode or the update will not be saved.
5.ResultSetHandler
定义:public interface ResultSetHandler<T>
子类:根据取出数据的不同选择不同的容器接收.前三个较为常用.
BeanHandler:将结果集中第一条记录封装到一个指定的javaBean中.
BeanListHandler:将结果集中每一条记录封装到指定的javaBean中,将这些javaBean在封装到List集合中.
ScalarHandler:它是用于单个数据。例如select count(*) from 表操作.
ArrayHandler:将结果集中的第一条记录封装到一个Object[]数组中,数组中的每一个元素就是这条记录中的每一个字段的值.
ArrayListHandler:将结果集中的每一条记录都封装到一个Object[]数组中,将这些数组在封装到List集合中.
ColumnListHandler:将结果集中指定的列的字段值,封装到一个List集合中.
MapHandler:将结果集中第一条记录封装到了Map< String,Object>集合中,key就是字段名称,value就是字段值.
MapListHandler:将结果集中每一条记录封装到了Map<String,Object>集合中,key就是字段名称,value就是字段值,在将这些Map封装到List集合中.
KeyedHandler:将结果集中每一条记录封装到Map<String,Object>,在将这个map集合做为另一个Map的value,另一个Map集合的key是指定的字段的值.
6.DbUtils
定义:public final class DbUtils extends Object
构造方法:public DbUtils()
静态方法:
public static void close(Connection conn/ResultSet rs/Statement stmt)throws SQLException{}:此方法有重载(共3个),可以关闭Connection/Statement/ResultSet.
public static void closeQuietly(Connection conn,Statement stmt,ResultSet rs){}:关闭资源,避免异常,此方法有重载(共4个),可以一次关闭3个,也可以分别关闭.
public static void commitAndClose(Connection conn)throws SQLException{}:Commits a Connection then closes it, avoid closing if null.
public static void commitAndCloseQuietly(Connection conn){}:Commits a Connection then closes it, avoid closing if null and hide any SQLExceptions that occur.
public static boolean loadDriver(ClassLoader classLoader,String driverClassName){}:Loads and registers a database driver class. If this succeeds, it returns true, else it returns false.有重载,可以直接传入driverClassName.
public static void rollback(Connection conn)throws SQLException{}:Rollback any changes made on the given connection.
public static void rollbackAndClose(Connection conn)throws SQLException{}:Performs a rollback on the Connection then closes it, avoid closing if null.
public static void rollbackAndCloseQuietly(Connection conn){}:Performs a rollback on the Connection then closes it, avoid closing if null and hide any SQLExceptions that occur.
7.代码演示:导包mysql-connector-java-5.1.39-bin.jar,commons-dbutils-1.6.jar,c3p0-0.9.1.2.jar(使用了前面自定义的MyC3P0工具类)
1 //定义一个类,要使用到BeanHandler类
2 public class Vegetables {
3 private int id;
4 private String name;
5 //空参构造--Eclipse快捷键:alt+shift+c
6 public Vegetables() {
7 super();
8 }
9 //满参构造--Eclipse快捷键:alt+shift+o
10 public Vegetables(int id, String name) {
11 super();
12 this.id = id;
13 this.name = name;
14 }
15 //覆写toString--Eclipse快捷键alt+shift+s
16 @Override
17 public String toString() {
18 return "Vegetables [id=" + id + ", name=" + name + "]";
19 }
20 //getter/setter--Eclipse快捷键alt+shift+r
21 public int getId() {
22 return id;
23 }
24 public void setId(int id) {
25 this.id = id;
26 }
27 public String getName() {
28 return name;
29 }
30 public void setName(String name) {
31 this.name = name;
32 }
33 }
34
35 import huguangqin.com.cnblogs_MyC3P0Utils.MyC3P0Utils;//使用了前面自定义的工具类
36 import java.util.List;
37 import org.apache.commons.dbutils.QueryRunner;
38 import org.apache.commons.dbutils.handlers.BeanHandler;
39 import org.apache.commons.dbutils.handlers.BeanListHandler;
40 import org.apache.commons.dbutils.handlers.ScalarHandler;
41
42 public class Demo {
43 @SuppressWarnings("all")//压制黄线警告
44 public static void main(String[] args) throws Exception {
45 // 获取QueryRunner对象
46 QueryRunner qr = new QueryRunner(MyC3P0Utils.getDataSource());
47 // 插入数据
48 String inertSQL = "INSERT INTO dbutil(id,name) VALUES(?,?)";
49 int i1 = qr.update(inertSQL, null, "白菜");
50 int i2 = qr.update(inertSQL, null, "豆腐");
51 int i3 = qr.update(inertSQL, null, "磨菇");
52 System.out.println(i1 + i2 + i3);
53
54 // 修改
55 String updateSQL = "UPDATE dbutil SET name = ? WHERE id = 1";
56 int i4 = qr.update(updateSQL, "小白菜");
57 System.out.println(i4);
58
59 // 查询1--ScalarHandler
60 String querySQL = "SELECT name FROM dbutil WHERE name Like '___'";
61 // 定义容器接收 ScalarHandler
62 ScalarHandler sh = new ScalarHandler();
63 String s = qr.query(querySQL, sh);
64 System.out.println(s);// 只返回一个值
65
66 // 查询2--BeanHandler
67 String querySQL2 = "SELECT * FROM dbutil";
68 BeanHandler bh = new BeanHandler(Vegetables.class);
69 Vegetables v = qr.query(querySQL2, bh);
70 System.out.println(v);// 只返回一个实例对象
71
72 // 查询3--BeanListHandler
73 BeanListHandler blh = new BeanListHandler(Vegetables.class);
74 List<Vegetables> list = qr.query(querySQL2, blh);// 返回List
75 for (Vegetables v1 : list) {
76 System.out.println(v1);
77 }
78 // 删除
79 String deleteSQL = "DELETE FROM dbutil";
80 int i5 = qr.update(deleteSQL);
81 System.out.println(i5);
82 }
83 }
84
最新文章
- 一键安装lamp环境 centos
- WebAPI的初步认识(CURD)
- iOS - UIStepper
- Note_Master-Detail Application(iOS template)_02_YJYAppDelegate.m
- Centos 6.5编译安装Nginx+php+Mysql
- C 猜数游戏
- springcloud(五):熔断监控Hystrix Dashboard和Turbine
- vue搭建项目前奏曲——vue-cli
- python 中 reversed()函数
- linux快速清空文件 比如log日志
- D1 java概述
- c->;log技巧
- FreeMarker内建函数
- 累计进度条 PSP
- kendoui仪表盘和柱状图 示例
- HAL_RTC_MspInit Msp指代什么?
- 找你妹+ipad+wifi,回顾那年的经典游戏
- ant design pro(二)布局
- jquery 实现动画效果(各种方法)
- 入门GitHub