学习了数据库连接池和maven之后
使用maven创建项目, 完成对数据库表的增删改查
要求:
1.使用数据库连接池 获取连接
2.使用类加载器加载配置文件获取数据库连接信息
3.不再手动导入jar包,需要在maven项目中的pom.xml 配置相关jar包信息
1.准备数据库
在MySQL中创建表并添加内容
USE db1
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int
);
--添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1);
2.在创建maven项目,在pom.xml中配置需要的jar包
<dependencies>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11_preview_9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
需要jar包 不知道配置文件怎么写可以去
Maven仓库官网
中查找
3.在resources创建配置文件druid.properties并编写数据库信息
driverClassName=com.mysql.jdbc.Driver
#服务器信息
url=jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true
#数据库账号密码
username=root
password=1234
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000
4.创建数据库连接池(加载配置文件时推荐使用类加载器)
需求分析:
在增删改查时都需要一条数据库连接,使用数据库连接池时不需要每次创建和关闭,使用时从连接池中拿就可以了。
所以在整个程序中连接池只需要创建一次。我们可以写着静态代码块中,随着类的加载而加载 并且只会执行一次!
创建DruidUtil类
用来创建连接池,获取数据库连接,和释放资源
*
* 在静态代码块中加载配置文件 随着类的加载而执行
* */
public class DruidUtil {
//以为在下面的获取数据库连接方法时会用到DataSource(数据库连接池对象)获取连接所以创建成员变量
private static DataSource ds;
/**
*
* 在静态代码块中加载配置文件 随着类的加载而执行
* */
static{
try {
Properties pro=new Properties();
//类加载器加载配置文件
InputStream in = Demo01.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(in);
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.在DruidUtil 类中继续编写获取数据库连接 和关闭数据库方法
获取连接需要多次用到 每次增删改查都需要用到,所以封装成静态方法 方便调用
释放资源同理
/**
获取连接 直接使用数据库连接池对象条用getConnection()方法
*/
public static Connection getConn () throws Exception {
return ds.getConnection();
}
/**
* 释放资源
* */
public static void close(Connection conn, Statement stm, ResultSet rs){
try {
if (conn!=null)conn.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
try {
if (stm!=null)stm.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
try {
if (rs!=null)rs.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
/**
*重载close方法
* */
public static void close(Connection conn,Statement stm){
close(conn,stm,null);
}
当查询时需要使用到ResultSet 对象 所以释放资源时需要三个参数
增删改时只需要两个 所以重载方法 再调用原方法 第三个参数传null即可;
6.编写与数据库对应的实体类Brand
/**
* 品牌
*
* alt + 鼠标左键:整列编辑
*
* 在实体类中,基本数据类型建议使用其对应的包装类型
*/
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
7.在测试类中编写增删改查方法 进行测试
查询
//注解用来运行方法
@Test
public void showBrand() throws Exception {
//因为获取连接创建的是静态方法 直接使用类名.方法名调取 获得连接即可
Connection conn= DruidUtil.getConn();
String sql="SELECT * FROM tb_brand";
//获取执行者对象
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
Brand brand;
List<Brand> brands=new ArrayList<Brand>();
//遍历ResultSet结果集 存入List
while (rs.next()){
brand=new Brand();
brand.setId(rs.getInt("id"));
brand.setBrandName(rs.getString("brand_name"));
brand.setCompanyName(rs.getString("company_name"));
brand.setOrdered(rs.getInt("ordered"));
brand.setDescription(rs.getString("description"));
brand.setStatus(rs.getInt("status"));
brands.add(brand);
}
//输出list查看
for (Brand brand1 : brands) {
System.out.println(brand1);
}
DruidUtil.close(conn,pstmt,rs);
}
添加数据
@Test
public void addBrand() throws Exception {
//获取数据库连接
Connection conn=DruidUtil.getConn();
String sql="insert into tb_brand (brand_name, company_name, ordered, description, status) values (?, ?, ?, ?, ?)";
//获取执行者对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置sql语句中的?值
pstmt.setObject(1,"云澈");
pstmt.setObject(2,"yc");
pstmt.setObject(3,55);
pstmt.setObject(4,"hhhh");
pstmt.setObject(5,4);
int i = pstmt.executeUpdate();
if (i>0){
System.out.println("添加成功");
}
//释放资源
DruidUtil.close(conn,pstmt);
}
删除数据
@Test
public void delectBrand() throws Exception {
//获取连接
Connection conn=DruidUtil.getConn();
String sql="DELETE from tb_brand where id=?";
//获取执行者对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置sql中的?值
pstmt.setObject(1,13);
int i = pstmt.executeUpdate();
if (i>0) System.out.println("删除成功");
//关闭资源
DruidUtil.close(conn,pstmt);
}
修改数据
@Test
public void test() throws Exception {
//获取连接
Connection conn=DruidUtil.getConn();
String sql="UPDATE tb_brand SET brand_name=? WHERE id=?";
//获取执行者对象
PreparedStatement pstmt = conn.prepareStatement(sql);
//设置sql中?的值
pstmt.setObject(1,"99999");
pstmt.setObject(2,10);
int i = pstmt.executeUpdate();
if (i>0) System.out.println("修改成功");
//释放资源
DruidUtil.close(conn,pstmt);
}