用到的有数据库连接池、JDBCTemplate
一、首先导入jar包
mysql
mysql-connector-java
8.0.25
compile
com.alibaba
druid
1.0.9
org.springframework
spring-core
4.1.2.RELEASE
compile
org.springframework
spring-jdbc
4.1.2.RELEASE
compile
org.springframework
spring-tx
4.1.2.RELEASE
compile
org.springframework
spring-beans
4.1.2.RELEASE
compile
下面解释一下什么是连接池和JDBCTemplate
连接池
1.1 什么是连接池
实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程,为了解决此类性能问题,通常情况我们采用连接池技术,来共享连接Connection。
这样我们就不需要每次都创建连接、释放连接了,这些操作都交给了连接池.
1.2 连接池的好处
用池来管理Connection,这样可以重复使用Connection。 当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池。
具体内容请看这篇文章https://juejin.cn/post/7032089873972461582
JDBCTemplate
介绍:
JDBC已经能够满足大部分用户最基本的需求,但是在使用JDBC时,必须自己来管理数据库资源如:获取PreparedStatement,设置SQL语句参数,关闭连接等步骤。
JdbcTemplate是Spring对JDBC的封装,目的是使JDBC更加易于使用。JdbcTemplate是Spring的一部分。JdbcTemplate处理了资源的建立和释放。他帮助我们避免一些常见的错误,比如忘了总要关闭连接。他运行核心的JDBC工作流,如Statement的建立和执行,而我们只需要提供SQL语句和提取结果。
Spring源码地址:github.com/spring-proj…
在JdbcTemplate中执行SQL语句的方法大致分为3类:
execute:可以执行所有SQL语句,一般用于执行DDL语句。
update:用于执行INSERT、UPDATE、DELETE等DML语句。
queryXxx:用于DQL数据查询语句。
call方法:用于执行存储过程、函数相关语句。
具体内容请看这篇文章https://juejin.cn/post/6987025481711222792
这个工具类把jdbc的内容拿出来封装成了一个类
package cn.itcast.travel.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
// 1. 声明静态数据源成员变量
private static DataSource ds;
// 2. 创建连接池对象
static {
// 加载配置文件中的数据
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
Properties pp = new Properties();
try {
pp.load(is);
// 创建连接池,使用配置文件中的参数
ds = DruidDataSourceFactory.createDataSource(pp);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 3. 定义公有的得到数据源的方法
public static DataSource getDataSource() {
return ds;
}
// 4. 定义得到连接对象的方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
// 5.定义关闭资源的方法
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
// 6.重载关闭方法
public static void close(Connection conn, Statement stmt) {
close(conn, stmt, null);
}
}
上面这个类加载的druid.properties文件。
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql:///travel?useSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT&allowPublicKeyRetrieval=true username=root password=root initialSize=5 maxActive=10 maxWait=3000



