切换主题
一、JDBC
一、概念
- JDBC是使用Java语言操作关系型数据库的一套API
- 全称(Java DataBase Connectivity)Java数据库连接
- 同一套Java代码,操作不同的关系型数据库

二、快速入门
1、使用步骤
创建工程,导入驱动jar包
注册驱动
javaClass.forName("com.mysql.jdbc.Driver");
获取连接
javaConnection conn = DriverManager.getConnection(url , username , password);
定义SQL语句
javaString sql = "update...";
获取执行SQL对象
javaStatement stmt = conn.createStatement();
执行SQL
javastmt.executeUpdate(sql);
处理返回结果
释放资源
可能出现的警告
Loading class
com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.将
javaClass.forName("com.mysql.jdbc.Driver");
改为
javaClass.forName("com.mysql.cj.jdbc.Driver");
2、示例
java
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//连接数据库
String url="jdbc:mysql://127.0.0.1:3306/test";
String user="root";
String password="123456";
Connection conn = DriverManager.getConnection(url, user, password);
//创建一个用于执行 SQL 语句的 Statement 对象
Statement stmt = conn.createStatement();
//定义SQL语句
String sql="update account set money = 1324 where username='李四'";
//执行SQL
int count=stmt.executeUpdate(sql); //受影响的行数
//关闭资源
stmt.close();
conn.close();
3、简化
可以删除这段代码
java
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
因为在xxx.jar
包的META-INF
文件夹的services
文件夹下的java.sql.Driver
已经有了这句话
三、JDBC API
1、DriverManager
- DriverManager(驱动管理类)作用:
- 注册驱动
- 获取数据库连接
2、Connection
- Connection(数据库连接对象)作用:
- 获取执行SQL的对象
- 管理事务
(1)获取执行SQL的对象
普通执行SQL对象
javaStatement createStatement()
预编译SQL的执行SQL对象:防止SQL注入
javaPreparedStatement prepareStatement(sql)
执行存储过程的对象
javaCallableStatement prepareCall(sql)
(2)事务管理
MySQL事务管理
开启事务
sqlbegin;
sqlstart transaction;
提交事务
sqlcommit;
回滚事务
sqlrollback;
JDBC事务管理:
Connection
接口中定义了3个对应的方法 开启事务
java//true为自动提交事务,false为手动提交事务,即开启事务 conn.setAutoCommit(boolean autoCommit);
提交事务
javaconn.commit();
回滚事务
javaconn.rollback();
Java代码示例
javatry{ conn.setAutoCommit(false); //sql操作... con.commit(); }catch(Exception e){ conn.rollback(); }
3、Statement
Statement作用
- 执行SQL语句
执行SQL语句
执行DML、DDL语句
javaint executeUpdate(sql)
返回值:
(1)DML语句影响的行数
(2)DDL语句执行后,执行成功也可能返回0
执行DQL语句
javaResultSet executeQuery(sql)
返回值:
(1)ResultSet结果集对象
4、ResultSet
封装了DQL查询语句的结果
(1)next
java
boolean next()
(1)将光标从当前位置向前移动一行
(2)判断当前行是否为有效行
(3)返回值:true:有效行,当前行有数据;false:无效行,当前行没有数据
(2)getXxx
java
xxx getXxx(参数)
(3)结合使用
java
while(rs.next()){
rs.getXxx(参数);
}
5、PreparedStatement
- 作用:
- 预编译SQL语句并执行:预防SQL注入问题
- SQL注入
- SQL注入是通过操作输入来修改事先定义好的SQL语句,用以达到执行代码对服务器进行攻击的方法
(1)获取PreparedStatement对象
java
// 创建 PreparedStatement 对象
PreparedStatement pstmt = conn.prepareStatement(sql);
String sql="select * from user where username = ? and password = ?";
(2)设置参数值
java
pstmt.setXxxx(参数1,参数2);
Xxxx:数据类型,如setString
、setInt
参数1:?
的位置编号,从1
开始
参数2:?
的值
(3)执行SQL
java
pstmt.executeUpdate(); //不需要再传递sql
四、数据库数据池
1、简介
- 数据库连接池是个容器,负责分配、管理数据库连接
- 它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
- 释放空闲时间超过最大空闲时间的数据库连接来避免因为没用释放数据库连接而引起的数据库连接遗漏
- 好处:
- 资源重用
- 提升系统响应速度
- 避免数据库连接遗漏
2、Druid连接池
链接:https://www.123pan.com/s/QvTuVv-QEjw.html
(1)使用步骤
- 导入jar包
druid-1.1.12.jar
- 定义配置文件
- 加载配置文件
- 获取数据库连接池对象
- 获取连接
(2)定义配置文件
properties
driverClassName=com.mysql.jdbc.Driver
#useSSL=false:不使用SSL连接
#useServerPrepStmts=true :使用服务器端准备的语句(Prepared Statements),这可以提高执行 SQL 语句的效率和安全性。
url=jdbc:mysql:///flask?useSSL=false&useServerPrepStmts=true
username=root
password=123456
#初始化连接数量
inititalSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000
(3)示例
java
public class Main {
public static void main(String[] args) throws Exception {
// 加载配置文件
Properties prop=new Properties();
prop.load(new FileInputStream("Druid_demo/src/druid.properties"));
// System.out.println(System.getProperty("user.dir"));
// 获取连接池对象
DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}
五、练习
对
tb_brand
表进行增删改查
1、建表tb_brand
sql
create table tb_brand(
id int auto_increment primary key not null unique comment '主键id',
brand_name varchar(255) not null comment '品牌名称',
company_name varchar(255) not null comment '公司名称',
ordered int not null comment '排序字段',
description varchar(255) not null comment '描述信息',
status int not null default 0 comment '状态'
) comment '品牌表';
insert into tb_brand (brand_name, company_name, ordered, description) values ('Redmi K70','小米',1,'雷军的小米公司');
insert into tb_brand (brand_name, company_name, ordered, description) values ('HuaWei mate60','华为',2,'任正非的华为公司');
insert into tb_brand (brand_name, company_name, ordered, description) values ('OPPO A5','oppo',3,'oppo的oppo公司');
2、新建实体类Brand
java
public class Brand {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
private Integer status;
public Brand() {
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
/**
* 获取
* @return id
*/
public Integer getId() {
return id;
}
/**
* 设置
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取
* @return brandName
*/
public String getBrandName() {
return brandName;
}
/**
* 设置
* @param brandName
*/
public void setBrandName(String brandName) {
this.brandName = brandName;
}
/**
* 获取
* @return companyName
*/
public String getCompanyName() {
return companyName;
}
/**
* 设置
* @param companyName
*/
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
/**
* 获取
* @return ordered
*/
public Integer getOrdered() {
return ordered;
}
/**
* 设置
* @param ordered
*/
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
/**
* 获取
* @return description
*/
public String getDescription() {
return description;
}
/**
* 设置
* @param description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取
* @return status
*/
public Integer getStatus() {
return status;
}
/**
* 设置
* @param status
*/
public void setStatus(Integer status) {
this.status = status;
}
public String toString() {
return "Brand{id = " + id + ", brandName = " + brandName + ", companyName = " + companyName + ", ordered = " + ordered + ", description = " + description + ", status = " + status + "}";
}
}
3、查询
java
public class BrandTest {
@Test
public void testSelectAll() throws Exception {
// 引入配置文件
Properties properties = new Properties();
// 加载配置文件
properties.load(new FileInputStream("src/druid.properties"));
// 获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection conn = dataSource.getConnection();
// 编写sql语句
String sql="select * from tb_brand";
// 获取preparedStatement对象
PreparedStatement ps=conn.prepareStatement(sql);
// 执行查找函数,返回结果集
ResultSet resultSet = ps.executeQuery();
List<Brand> brands=new ArrayList<>();
Brand brand=null;
while (resultSet.next()){
int id = resultSet.getInt("id");
String brandName = resultSet.getString("brand_name");
String companyName = resultSet.getString("company_name");
int ordered = resultSet.getInt("ordered");
String description = resultSet.getString("description");
int status = resultSet.getInt("status");
brand=new Brand();
brand.setId(id);
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(ordered);
brand.setDescription(description);
brand.setStatus(status);
brands.add(brand);
}
System.out.println(brands);
resultSet.close();
ps.close();
conn.close();
}
}
4、新增
java
@Test
public void testAdd() throws Exception {
//引入配置文件
Properties properties = new Properties();
//加载配置文件
properties.load(new FileInputStream("src/druid.properties"));
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection conn = dataSource.getConnection();
String sql = "insert into tb_brand (brand_name, company_name, ordered, description) values (?,?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "modelY");
preparedStatement.setString(2, "特斯拉");
preparedStatement.setInt(3, 10);
preparedStatement.setString(4, "马斯克的描述");
int count = preparedStatement.executeUpdate();
System.out.println(count > 0);
preparedStatement.close();
conn.close();
}
5、修改
java
@Test
public void testUpdate() throws Exception {
Integer id = 4;
String brandName = "xxx1";
String companyName = "xxx2";
Integer ordered = 100;
String description = "xxx";
//引入配置文件
Properties properties = new Properties();
//加载配置文件
properties.load(new FileInputStream("src/druid.properties")
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection conn = dataSource.getConnection();
String sql = "update tb_brand set brand_name = ?, company_name = ?, ordered = ?, description = ? where id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, brandName);
preparedStatement.setString(2, companyName);
preparedStatement.setInt(3, ordered);
preparedStatement.setString(4, description);
preparedStatement.setInt(5, id);
int count = preparedStatement.executeUpdate();
System.out.println(count > 0);
preparedStatement.close();
conn.close();
}
6、删除
java
@Test
public void testDelete() throws Exception {
Integer id = 4;
//引入配置文件
Properties properties = new Properties();
//加载配置文件
properties.load(new FileInputStream("src/druid.properties"));
//获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection conn = dataSource.getConnection();
String sql = "delete from tb_brand where id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, id);
int count = preparedStatement.executeUpdate();
System.out.println(count > 0);
preparedStatement.close();
conn.close();
}