一、JDBC快速入门
(一)涉及的API
涉及的API(java.sql.* 或 javax.sql.*)
1. DriverManager类 管理不同的驱动
2. Connection 接口 java应用和数据库的连接
3. Statement 接口 用于执行sql语句
4. ResultSet 接口 保存查询的结果
(二)使用
1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
2.获取连接对象
String URL = "jdbc:mysql://localhost:3306/数据库名";
String USERNAME = "root";
String PASS = "password";
Connection connection = DriverManager.getConnection(URL,USERNAME,PASS);
3.创建命令对象
Statement stat = connection.createStatement();
4.执行sql命令返回结果
int i = statement.executeUpdate(sql);//执行增删改,返回受影响的行数
ResultSet rs = staetment.executeQuery(sql);//执行查询
5.处理结果
if(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
}
6.释放资源
rs.close();
stat.close();
connection.close();
二、数据库连接池之c3p0
c3p0是一个开源组织提供的一个数据库连接池,速度相对较慢,但是稳定性比较好。
(一)c3p0需要的两个jar包
1、c3p0-0.9.5.2.jar
2、mchange-commons-java-0.2.11.jar
(二)两种使用方式
1、代码配置
①创建c3p0连接池对象
ComboPooledDataSource cpds = new ComboPooledDataSource();
②配置信息(必配)
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/0831db");//0831db是要使用的数据库名
cpds.setUser("root");//登录数据库的用户名
cpds.setPassword("root");//登录数据库的密码
③选配信息(根据需求配置,也可以不配置)
cpds.setInitialPoolSize(10);
cpds.setMaxPoolSize(100);
cpds.setMinPoolSize(10);
cpds.setMaxIdleTime(30);
④从池子中获取连接
Connection connection = cpds.getConnection();
2、配置文件方式(推荐使用)
①创建c3p0.properties放在src目录下
##必配
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/0831db
c3p0.user=root
c3p0.password=root
##选配
c3p0.maxPoolSize=100
c3p0.minPoolSize=10
c3p0.initialPoolSize=10
c3p0.maxIdleTime=30
②创建连接池对象,自动读取配置文件信息
ComboPooledDataSource cpds = new ComboPooledDataSource();
Connection connection = null;
try{
connection = cpds.getConnection();
Statement statement = connection.createStatement();
String sql = "delete from users where uid=4";
int update = statement.executeUpdate(sql);
System.out.println("影响行数"+update);
}catch (SQLException e){
e.printStackTrace();
}finally{
try{
connection.close();
}catch(SQLException){
e.printStackTrace();
}
}
3、总结
c3p0连接池,需要导入两个jar包,写一个配置文件,缺一不可
三、数据库连接池之Druid
(一)jar包
druid连接池只需要一个jar包
druid-1.1.10.jar
(二)使用
1、配置文件
①编写druid.properties放在src目录下
driverClassName=com.mysql.jdbc.Driveer
url=jdbc:mysql://localhost:3306/0831db?rewriteBatchedStatements=true
username=root
password=root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000
②读取配置文件
Properties properties = new Properties();
InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
properties.load(stream);
③创建druid连接池对象
//创建druid连接池对象
Datasource dataSource = DruidDataSourceFactory.createDatasource(properties);
//获取连接池的连接对象
Connection connection = dataSource.getConnection();
//创建命令对象
Statemnet statement = connection.createStatement();
//执行命令,返回结果
String sql = "select * from users where uid=1";
ResultSet resultSet = statement.executeQuery(sql);
//处理结果
if(resultSet.next()){
int uid = resultSet.getInt("uid");
String uname = resultSet.getString("uname");
String usex = resultSet.getString("usex");
String ucardno = resultSet.getString("ucardno");
int cid = resultSet.getInt("c_id");
System.out.println(uid+uanme+usex+ucardno+cid);
}
//将连接放回池子中
connection.close();
四、dbutils使用
(一)简介
commons-dbutils 是 Apache 组织提供的一个开源JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。
(二)API
1、核心API
QueryRunner:通过该对象调用不同的犯法实现对数据库的增删改查操作
构造方法:new QueryRunner();
new QueryRunner(DataSource ds)
ResultSetHandler:结果集映射,主要应用查询操作,接口单行查询、多行查询、聚合查询
2、实现类
BeanHandler:将ResultSet结果集中第一行转换为javaBean对象的映射过程
BeanListHandler:将ResultSet结果集中的数据转换为List集合对象的映射过程
ScalarHandler:将一个ResultSet列转换为一个对象
(三)常用方法
1、操作:update()
public int update(Connection conn,String sql,Object... params)
public int update(String sql,Object... params)throws SQLException
用来执行插入、更新、删除操作
2、查询:query()
public Object qurey(Connection conn,String sql,ResultSetHandler rsh,Object... oarams)throws SQLException
执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法自行处理PreparedStatement 和 ResultSet 的创建和关闭
public Object query(String sql,ResultSetHandler rsh,Object... params)
代码示例:
static ComboPooledDataSource ds = null;
static QueryRunner qr = null;
static{
ds = new ComboPooledDataSource();//创建c3p0的连接池对象
qr = new QueryRunner(ds);
}
//封装增删改方法
public int update(String sql,Object...params){
try {
return qr.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
(四)基本使用
1、下载导包
commons-dbutils-1.7.jar
2、使用
①创建核心对象
QueryRunner qr = new QueryRunner();
②执行命令
int update = qr.update(connection,sql,params); // 执行增删改
T t = qr.query(connection,sql,new BeanHandler,params);
List t = qr.query(connection,sql,new BeanListHandler,params);
Object t = qr.query(connection,sql,new ScalerHandler,params);
五、通用DAO封装
(一)什么是DAO
Data Access Object访问数据信息的类和接口,包括了对数据的CRUD(Create、Retrival、Update、Delete),而不包含任何业务相关的信息
(二)作用
为了实现功能的模块化,更有利于代码的维护和升级
(三)封装
package com.offcn.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
public class BaseDao<T> {
static ComboPooledDataSource ds = null;
static QueryRunner qr = null;
static{
ds = new ComboPooledDataSource();//创建c3p0的连接池对象
qr = new QueryRunner(ds);
}
//封装增删改方法
public int update(String sql,Object...params){
try {
return qr.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//单行查询
public T queryOne(String sql,Class<T> clazz,Object... params){
try {
return qr.query(sql,new BeanHandler<>(clazz),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//多行查询
public List<T> queryMore(String sql, Class<T> clazz, Object...params){
try {
return qr.query(sql,new BeanListHandler<>(clazz),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
//聚合查询
public Number queryScar(String sql,Object...params){
try {
return qr.query(sql,new ScalarHandler<Number>(),params);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}