一。
- JDBC规范:
1.导入jar包
2.加载驱动 com.mysql.cj.jdbc.Driver
3.通过DriverManager 获得连接 Connection
url username password
url: jdbc:mysql://localhost:3306/database
jdbc:mysql:///database
4.Statement PreparedStatement
5.执行SQL: execute() executeUpdate() executeQuery()
6.如果有结果, 处理结果 ResultSet - next()
7.释放资源 close()
二。连接池
-
①.连接池 - 存储连接
好处:
1.在连接池中的连接, 在连接池初始化时就已经创建好,在使用连接的时候, 就可以快速获得连接对象
2.连接使用完成后, 可以将连接归还给连接池, 让连接重复使用②.JDBC提供的连接池规范 DataSource
市面常见连接池:
Apache - dbcp
C3P0
alibaba - druid
三。C3P0
-
使用c3p0第三方连接池步骤
a.导入jar包
b.编写配置文件 c3p0-config.xml或者c3p0.properties
位置: 必须在类路径的根目录中 -> src中
c.创建连接池对象 ComboPooledDataSource通过连接池获得的连接关闭后, 连接对象返回给连接池, 并且引用设置为null
通过JDBC获得的连接关闭后, 连接对象还在, 但是状态是"已关闭", 不能再使用
c3p0普通版
public class C3p0Quickstart {//连接池
public static void main(String[] args) throws PropertyVetoException, SQLException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "com.mysql.cj.jdbc.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/work01?serverTimezone=GMT" );
cpds.setUser("liuliudr");
cpds.setPassword("123456");
Connection connection=cpds.getConnection();
//connection.close();关闭连接
}
}
-----------------------------------------------------
c3p0封装版
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class C3p0Configuration { //C3P封装版
public static void main(String[] args) throws SQLException {
//导入jar包
// c3p0配置文件必须在类路径的根目录中:src那层
//创建连接对象
ComboPooledDataSource dataSource=new ComboPooledDataSource();
Connection connection;
for (int i=0;i<21;i++){// 超出连接池最大超度时如果没有关闭一个或几个,会TimeoutException超时
connection=dataSource.getConnection();
if(i==15){
connection.close();
}
System.out.println(connection);
}
}
}
---------------------------------------------------
配置文件
<?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/work01?serverTimezone=GMT</property>
<property name="user">liuliudr</property>
<property name="password">123456</property>
<!-- 初始化连接数-->
<property name="initialPoolSize">10</property>
<!-- 最大连接数-->
<property name="maxPoolSize">20</property>
<!-- 最小连接数-->
<property name="minPoolSize">5</property>
<!-- 等待时间-->
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web_07</property>
<property name="user">root</property>
<property name="password">123</property>
</named-config>
</c3p0-config>
三。Druid连接池使用步骤
- a.导入jar包
b.编写配置文件
位置和名字都随意
c.通过工厂创建连接池对象
DruidDataSourceFactory.createDataSource(Properties)
Druid连接池使用方法
public class Diuid1 {
public static void main(String[] args) throws Exception {
//导入jar包
//配置文件可放在任意位置,其需要手动读取
//创建一个 Properties 属性集
Properties pros= new Properties();
pros.load(Diuid1.class.getResourceAsStream("druid.properties"));
//Druid 提供了一个获得DataSource的工厂类
DataSource dataSource= DruidDataSourceFactory .createDataSource(pros);
//通过工厂类获取连接
Connection connection=dataSource.getConnection();
System.out.println(connection);
Connection connection1= DruidUtils.getConnection(); //用druid连接池的封装获得连接
System.out.println(connection1);
}
}
druid封装版
public class DruidUtils {//Driud连接池封装
private static DataSource dataSource;
static {//dataSourse初始化
Properties properties=new Properties();
try {
properties.load(DruidUtils.class.getResourceAsStream("druid.properties"));
dataSource= DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
-----------------------------------------------------
配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/work01?serverTimezone=GMT
username=liuliudr
password=123456
initialSize=5
maxActive=10
maxWait=3000
四。JdbcTemplate
- a.导包
b.创建JdbcTemplate对象
c.使用jdbcTemplate操作数据库
update(sql): DML操作
queryForMap(sql): 只能处理一条结果集,
将列名作为key, 列中的数据作为value封装到map中
map -> JavaBean, 工具可以使用
queryForList(sql): 将查询出来的结果集,
每一行封装为一个map, 再将这个map封装到list中
queryForObject(sql, Class): 查询单列数据
并且将这一列数据, 转换成Class对应的类型对象
query(sql, RowMapper)
RowMapper: 已知实现类 BeanPropertyRowMapper
new BeanPropertyRowMapper(Class)
注意: 实体类的属性名 和 表的字段名一致
public class Demo1 {
@Test
public void t1() {
//导入jdbc的相关jar包
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
//执行Dml方法
//sql 增
String sql = "insert into emp values (?,?,?,?,?,?,?,?);";
//updat
jdbcTemplate.update(sql, 8001, "JALLP", "CLERK", 7902, "1998-3-29", 888, 666, 10);
}
@Test
public void t2() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
//sql 删
String sql = "delete from emp where ename = ?;";
//updat
jdbcTemplate.update(sql, "JALLP");
}
@Test
public void t3() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
//sql 改
String sql = "update emp set deptno=? where ename = ?;";
//updat
jdbcTemplate.update(sql, 30, "SUSAN");
}
//DQL查
@Test
public void t6() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
//用query(sql, new BeanPropertyRowMapper<>(class))遍历表会自动封装成Class
// Map<String,Object> map=new HashMap<>();
// String sql = "select * from emp ;";
// map= jdbcTemplate.queryForMap(sql);
// /*
// 抛出错误 Incorrect result size: expected 1, actual 15
// 结果希望有一个结果有15个
// */
// System.out.println(map);
Map<String,Object> map=new HashMap<>();
// String sql = "select count(ename) from emp;";
String sql = "select count(*)from emp where deptno=20 ;";
map= jdbcTemplate.queryForMap(sql); //queryForMap()返回map.只能返回一个列的一个值。
System.out.println(map);
}
@Test
public void t7() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
List<Map<String,Object>> list = new ArrayList<>();
String sql = "select * from emp;";
//queryForList()返回集合。元素是map类型。key为表中所有的字段,value是字段的值。
list= jdbcTemplate.queryForList(sql);
list.stream().forEach(System.out::println);
}
@Test
public void t5() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
List<Emp> list = new ArrayList<>();
String sql = "select * from emp;";
/*
用query(sql, new RowMapper)遍历表,并且将表的数据封装成对象
query会自动遍历表的每一行
*/
jdbcTemplate.query(sql, new RowMapper<Emp>() {
// RowMapper接口的实现方法mapRow用来封装每行的数据
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
Date hiredate = rs.getDate("hiredate");
int sal = rs.getInt("sal");
int comm = rs.getInt("comm");
int deptno = rs.getInt("deptno");
Emp emp = new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno);
list.add(emp);
return emp;
}
});
list.stream().forEach(System.out::println);
}
@Test
public void t4() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
//用query(sql, new BeanPropertyRowMapper<>(class))遍历表会自动封装成Class。返回值是封装的集合。集合里每个元素是map类型
List<Emp> list = new ArrayList<>();
String sql = "select * from emp;";
/*
BeanPropertyRowMapper()是query里给的已经实现的方法。但是用它必须要让Emp对象的成员变量
和表中字段相同。并且要用Interger等封装类型。要加上无参构造器
*/
list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
list.stream().forEach(System.out::println);
}
@Test
public void t11(){//查询总数
JdbcTemplate jdbcTemplate=new JdbcTemplate(DruidUtils.getDataSource());
String sql = "select count(*)from emp ";
long l= jdbcTemplate.queryForObject(sql, long.class);
System.out.println(l);
}
}
- 线程池好处:
1.线程池中的线程 在线程池初始化时就已经创建好
在使用线程的时候, 就可以快速获得线程对象
2.线程使用完毕后, 可以归还给线程池, 让线程做到重复利用
本文详细介绍JDBC规范,包括连接池概念与实现,如C3P0和Druid的配置与使用,以及JdbcTemplate的高级操作。涵盖数据库连接管理、资源释放、SQL执行和结果处理,适合数据库操作优化与性能提升的学习。
1564

被折叠的 条评论
为什么被折叠?



