1.C3P0
配置文件c3p0-config.xml
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test?serverTimezone=UTC</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
</named-config>
</c3p0-config>
数据库连接池的创建和使用:
public class C3P0Test {
public static void main(String[] args) throws SQLException, IOException {
//创建数据库连接池
DataSource ds = new ComboPooledDataSource("c3p0-config.xml");
//获取连接
Connection conn = ds.getConnection();
System.out.println(conn);
//提取数据库中的Blob类型的数据
String sql = "select image from emp where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1015);
ResultSet rs = ps.executeQuery();
rs.next(); //注意这里一定要用rs.next(),将结果集的指针指向下一行,否则会出现java.sql.SQLException: Before start of result set
InputStream is = rs.getBinaryStream(1);
FileOutputStream fos = new FileOutputStream("image2.jpg");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
fos.write(bytes,0,len);
}
fos.close();
is.close();
//3.关闭连接
JDBCUtils2.closeResource(conn, ps,rs);
}
}
2.Druid
配置文件druid.properties
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
driverClassName=com.mysql.cj.jdbc.Driver
username=root
password=123456
数据库连接池的创建和使用:
public class DruidTest {
public static void main(String[] args) throws Exception {
//1.加载配置文件
Properties properties = new Properties();
InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
//2.创建数据库连接池
DataSource ds = DruidDataSourceFactory.createDataSource(properties);
//3.获取连接
Connection conn = ds.getConnection();
System.out.println(conn);
//4.提取数据库中的Blob类型的数据
String sql = "select image from emp where id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1015);
ResultSet rs = ps.executeQuery();
rs.next(); //注意这里一定要用rs.next(),将结果集的指针指向下一行,否则会出现java.sql.SQLException: Before start of result set
InputStream is1 = rs.getBinaryStream(1);
FileOutputStream fos = new FileOutputStream("image2.jpg");
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is1.read(bytes)) != -1) {
fos.write(bytes,0,len);
}
fos.close();
is1.close();
//5.关闭连接
JDBCUtils2.closeResource(conn, ps,rs);
}
}
3.使用数据库连接池和DbUtils写的工具类JDBCUtils2.java
/**
* 使用数据库连接池和DbUtils实现
*/
public class JDBCUtils2 {
static private DataSource ds = null;
//由于数据库连接池只需创建一次,因此使用静态代码块,在使用时只加载一次
static {
try {
Properties properties = new Properties();
properties.load(JDBCUtils2.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭资源
public static void closeResource(Connection conn, Statement statement){
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(statement);
}
//关闭资源
public static void closeResource(Connection conn, Statement statement, ResultSet resultSet){
DbUtils.closeQuietly(conn);
DbUtils.closeQuietly(statement);
DbUtils.closeQuietly(resultSet);
}
}
4.DbUtils的简单使用
作用:主要是用来简化JDBC中的操作, DbUtils:提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:
– public static void close(…) throws java.sql.SQLException:
DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。
– public static void closeQuietly(…):
这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLEeception。
– public static void commitAndCloseQuietly(Connection conn):
用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。
– public static boolean loadDriver(java.lang.String driverClassName):
这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。
5.QueryRunner类
创建QueryRunner对象的两种方式:
• 该类简单化了SQL查询,它与ResultSetHandler组合在一起使用可以完成大部分的数据库操作,能够大大减少编码量。
• QueryRunner类提供了两个构造方法:
– 默认的构造方法
– 需要一个 javax.sql.DataSource来作参数的构造方法。
主要方法:
• public Object query(Connection conn, String sql, Object[] params,ResultSetHandler rsh) throws SQLException:
执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理
PreparedStatement 和 ResultSet 的创建和关闭。
• public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException:
几乎与第一种方法一样;唯一的不同在于它不将数据库连接提供给方法,并且它是从提供给构造方法的数据源(DataSource)
或使用的setDataSource 方法中重新获得 Connection。
• public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException :
执行一个不需要置换参数的查询操作。
• public int update(Connection conn, String sql, Object[] params) throws SQLException:
用来执行一个更新(插入、更新或删除)操作。
• public int update(Connection conn, String sql) throws SQLException:
用来执行一个不需要置换参数的更新操作。
6.ResultSetHandlar类
• 该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。
• ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)
ResultSetHandlar接口的实现类:
• ArrayHandler:把结果集中的第一行数据转成对象数组。
• ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
• BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
• BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
• ColumnListHandler:将结果集中某一列的数据存放到List中。
• KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。
• MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
• MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到Lis •
• ScalarHandlar:用于查询特殊的数据,如count(*)等
7.以上的宗和运用
public class DBUtilsTest {
@Test
public void test1() throws SQLException {
Connection conn = JDBCUtils2.getConnection();
QueryRunner qr = new QueryRunner();
//BeanListHandler 查询结果封装成对象的list
String sql = "SELECT id,ename name,job_id jobId,salary FROM emp WHERE id < ? ";
List<Employee> query = qr.query(conn, sql, new BeanListHandler<Employee>(Employee.class), 1015);
System.out.println(query);
//BeanHandler 将查询结果封装成JavaBean对象
String sql1 = "select id,ename name,job_id,salary from emp where id = ?";
Employee query1 = qr.query(conn, sql1, new BeanHandler<Employee>(Employee.class), 1015);
System.out.println(query1);
//ScalarHandler,用于查询特殊的数据
String sql2 = "select count(*) from emp";
long query2 = (long) qr.query(conn, sql2, new ScalarHandler<>()); //注意这里count()返回的是long类型的数据
System.out.println(query2);
}
}