一、传统的jdbc连接方式及其工具类构建
二、数据库连接池Druid使用及其工具类构建
三、SpringJDBC中JDBCTemplate的使用
数据库的准备(新建数据库):
-- MySQL dump 10.13 Distrib 8.0.17, for Win64 (x86_64)
--
-- Host: localhost Database: gamemanager
-- ------------------------------------------------------
-- Server version 5.6.45-log
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `game`
--
DROP TABLE IF EXISTS `game`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `game` (
`game_id` smallint(6) NOT NULL,
`game_name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`game_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `game`
--
LOCK TABLES `game` WRITE;
/*!40000 ALTER TABLE `game` DISABLE KEYS */;
INSERT INTO `game` VALUES (1,'D'),(2,'D'),(3,'C');
/*!40000 ALTER TABLE `game` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `user` (
`user_id` smallint(6) NOT NULL,
`username` varchar(20) DEFAULT NULL,
`passwords` varchar(20) DEFAULT NULL,
`age` tinyint(4) DEFAULT NULL,
`sex` char(2) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'user1','123',12,'nv'),(2,'user2','123',45,'nv'),(3,'user3','123',32,'nv');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-04-03 22:32:58
一、传统的jdbc连接方式及其工具类构建
1、建立jdbc的连接步骤:
(1)导入驱动包mysql-connector-java-5.1.32.jar(该驱动包是对jdk中sql包接口的实现)
(2)注册驱动(即将驱动包加载进来)
(3)获取数据库连接
(4)获取sql语句执行对象PreparedStatement;Statement;
(5)执行sql语句获得结果集resultSet
(6)处理结果
(7)释放连接(避免浪费内存资源
package com.djn.JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCTest {
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
String url = "jdbc:mysql://127.0.0.1:3306/gamemanager";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
// 获取statement,preparedStatement
String sql = "select * from user where user_id=?";
prepareStatement = connection.prepareStatement(sql);
// 设置参数
prepareStatement.setInt(1, 1);
// 执行查询
rs = prepareStatement.executeQuery();
// 处理结果集
while (rs.next()) {
System.out.println(rs.getString("username"));
System.out.println(rs.getString("passwords"));
}
} finally {
// 关闭连接,释放资源
if (rs != null) {
rs.close();
}
if (prepareStatement != null) {
prepareStatement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
这种形式的连接代码复用性差,每次需要访问数据库的时候都需要按照以上步骤书写代码,因此把加载驱动、连接数据库以及释放连接的过程提取出来,可以直接调用该工具包来获取连接,释放资源,提高代码复用性。
该工具类的创建过程:
(1)新建JDBCUtils 类,封装加载驱动、连接数据库以及释放连接的过程
package com.djn.JDBC;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Statement;
public class JDBCUtils {
private static Connection connection = null;
private static String URL;
private static String usename;
private static String password;
/*
* 新建一个jdbc的工具类(获取连接对象、释放连接资源的步骤封装起来
* 1、创建获取连接
* 1.1定义静态代码块,在代码块中注册驱动、获取properties文件中的url、usename、password
* 1.2返回connection对象
* 2、创建释放资源的方法
*/
static {
// 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 获取properties文件的绝对路径
/*ClassLoader classLoader = GetPathDemo.class.getClassLoader();
URL source = classLoader.getResource("JDBC.properties");
String path = source.getPath();
System.out.println(path);*/
// 相对路径
path = "src/JDBC.properties";
// 获取文件内容
Properties properties = new Properties();
try {
properties.load(new FileReader(path));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL = properties.getProperty("url");
usename = properties.getProperty("usename");
password = properties.getProperty("password");
}
public static Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, usename, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection, PreparedStatement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Connection connection = JDBCUtils.getConnection();
String sql = "select * from user where user_id=1";
PreparedStatement statement = null;
ResultSet set = null;
try {
statement = connection.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
set = statement.executeQuery();
} catch (SQLException e) {
System.out.println(e);
}
try {
set.next();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(set.getString(2) + " " + set.getString("passwords"));
JDBCUtils.close(connection, statement);
}
}
(2)新建JDBC.properties配置文件
url=jdbc:mysql:///gamemanager
usename=root
password=root
这种形式来连接释放数据库资源,一定程度上提高了代码的复用性,但每次调用都需要连接数据库,释放连接,要知道每次建立连接都需要花费较大代价来建立连接,如果比较多连接请求的话会造成资源浪费,为了解决这个问题,引入了数据库连接池的概念。
二、数据库连接池Druid使用及其工具类构建
数据库连接池:就是一个存储了较多连接对象的容器(即池子),每次需要连接数据库时,只需要从池子中调用一个连接对象出来使用,使用过后把连接对象归还到池子里。
这里介绍一个由阿里巴巴开发的一个数据库连接池Druid;
使用过程:
(1)导入jar包:druid-1.1.21.jar
(2)新建druid.properties配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///gamemanager
username=root
password=root
#初始化连接对象的数量
initialSize=5
#最大连接对象数量
maxActive=10
#最大等待时间(超过该时间未能获得连接,报错,单位为秒
maxWait=1000
(3)获得数据库连接池对象(DataSource)
Properties properties = new Properties();
properties.load(new FileReader("src/druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
(4)使用datasource获得连接
Connection connection = dataSource.getConnection();
这样的方式使用数据库连接池不便于代码复用,因此将数据库连接池创建,连接的获得、归还过程封装起来,构造druid的工具类DruidUtils,使用该工具可以直接获取连接,归还连接。
package com.djn.JDBC;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mysql.jdbc.Statement;
/*
* 定义数据库连接池druid的工具类
* 方法:
* 1、获取连接对象
* 2、归还连接对象
* 3、获取连接池对象
* 步骤:
* 1、导入druid-1.1.21.jar包
* 2、建立配置文件druid.properties
* 3、在静态代码块中初始化连接池
* 4、构建对外方法
*/
public class DruidUtils {
private static DataSource dataSource = null;
static {
Properties properties = new Properties();
try {
properties.load(new FileReader("src/druid.properties"));
} catch (IOException e) {
e.printStackTrace();
}
try {
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(ResultSet set, Statement statement, Connection connection) {
if(set != null) {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static DataSource getDataSource() {
return dataSource;
}
public static void main(String[] args) {
Connection connection = null;
for(int i=1; i<=10; i++) {
connection = DruidUtils.getConnection();
System.out.println(i+" "+connection);
}
}
}
这种方式虽然方便、较为节约资源地获取连接,但是获取连接后还是需要新建statement对象,再执行sql语句,处理结果,为了将这些代码提高复用性,需要引入SpringJDBC框架的JDBCTemplate对象
三、SpringJDBC中JDBCTemplate的使用
JDBCTemplate:封装了新建statement对象的过程,不过还是需要建立数据库连接池作为参数传入该对象,通过该对象的方法可以直接执行sql语句。
使用步骤:
1、导入jar包:
commons-logging-1.2.jar、spring-beans-5.2.4.RELEASE.jar
spring-core-5.2.4.RELEASE.jar、spring-jdbc-5.1.2.RELEASE.jar
spring-tx-5.1.2.RELEASE.jar
2、新建JDBCTempalte类对象(传入数据库连接池对象dataSource)
3、使用JDBCTempalte类对象的方法即可
update(sql) 执行增删改操作
queryForMap()执行查找,将结果返回为Map
queryForList()执行查找,将结果返回为List
query()执行查找,将结果返回为JavaBean
queryForObject()执行查找,将结果返回为object
package com.djn.JDBC;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
/*
* 使用JDBCTemplate
* 1、导入jar包:
* commons-logging-1.2.jar、spring-beans-5.2.4.RELEASE.jar
* spring-core-5.2.4.RELEASE.jar、spring-jdbc-5.1.2.RELEASE.jar
* spring-tx-5.1.2.RELEASE.jar
* 2、新建JDBCTempalte类对象(传入数据库连接池对象dataSource)
* 3、使用JDBCTempalte类对象的方法即可
* update(sql) 执行增删改操作
* queryForMap()执行查找,将结果返回为Map
* queryForList()执行查找,将结果返回为List
* query()执行查找,将结果返回为JavaBean
* queryForObject()执行查找,将结果返回为object
*/
public class JDBCTemplateDemo {
public static void main(String[] args) {
DataSource dataSource = DruidUtils.getDataSource();//获取DruidUtils工具类中建立的连接池对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "update game set game_name='D' where game_id=?";
//第一个参数为sql语句,第二个参数表示sql的第一个?的值,以此类推
int count = jdbcTemplate.update(sql, 2);
System.out.println(count);
}
}
附Java工程的结构图