目录
1.概念:
jdbc (Java DataBase Connectivity java数据库连接)就是使用Java语言操作关系型数据库的一套API
我们开发的同一套Java代码是无法操作不同的关系型数据库,因为每一个关系型数据库的底层实现细节都不一样。如果这样,问题就很大了,在公司中可以在开发阶段使用的是MySQL数据库,而上线时公司最终选用oracle数据库,我们就需要对代码进行大批量修改,这显然并不是我们想看到的。我们要做到的是同一套Java代码操作不同的关系型数据库,而此时sun公司就指定了一套标准接口(JDBC),JDBC中定义了所有操作关系型数据库的规则。众所周知接口是无法直接使用的,我们需要使用接口的实现类,而这套实现类(称之为:驱动)就由各自的数据库厂商给出。
JDBC本质
-
官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口
-
各个数据库厂商去实现这套接口,提供数据库驱动jar包
-
我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类
JDBC好处
-
各数据库厂商使用相同的接口,Java代码不需要针对不同数据库分别开发
-
可随时替换底层数据库,访问数据库的Java代码基本不变
以后编写操作数据库的代码只需要面向JDBC(接口),操作哪儿个关系型数据库就需要导入该数据库的驱动包,如需要操作MySQL数据库,就需要再项目中导入MySQL数据库的驱动包。
如果没有请自动下载,或私信找我要
2.把驱动导入使用
1.在当前模块下创建一个新的lib文件夹
2.将驱动复制到lib文件夹下
3.选中 右键 找到 add as library
4.当出现这种情况 说明已经 成功
以上也是 jar包的导入过程
3.连接数据库
// * 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
// ip 端口号 连接库名
// ?useSSL=false 把警告去掉
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
// 获取连接
Connection con = DriverManager.getConnection(url, username, passwd);
System.out.println(con);
打印结果,
如果出这种打印结果,恭喜你,数据库连接成功
如果这样,不要慌这只是一个警告, 在数据库名字后面加上 ?useSSL=false 就ok了
4.执行sql语句(对数据进行增删改查)
数据库结构
4.1:添加数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 注册
Class.forName("com.mysql.jdbc.Driver");
// 连接
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
Connection con = DriverManager.getConnection(url, username, passwd);
// 编写sql 语句
String sql = "INSERT into work(ename,joindata,salary,bonus) VALUES('老六','2002-06-22',20000,40)";
// 获取执行sql的对象 Statement
Statement statement = con.createStatement();
// 执行sql
int i = statement.executeUpdate(sql);//受影响的行数
System.out.println("受影响的函数为 " + i);
// 释放资源
con.close();
}
}
这里只是增加,删除,修改 都一样的 就该下sql语句
4.2修改数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
Connection con = DriverManager.getConnection(url,username,passwd);
// System.out.println(con);
// 编写 sql 语句
String sql = "update work set ename = '老七' where ename = '老六'";
// 执行 sql语句
Statement statement = con.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
con.close();
}
}
4.3修改数据
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 注册
Class.forName("com.mysql.jdbc.Driver");
// 连接
// jdbc:mysql://127.0.0.1:3306/java19
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
// 连接
Connection con = DriverManager.getConnection(url, username, passwd);
String sql = "delete from work where id = 17";
Statement statement = con.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
}
}
4.4查看数据
我们要定义一个类 worker类,因为 数据库里的每一行都相当于一个对象 ,将数据封装成对象,存到集合中,在进行查看
数据:
worker类
public class Worker {
private int id;
private String name;
private String joindata;
private double salary;
private double bonus;
public Worker() {
}
public Worker(int id, String name, String joindata, double salary, double bonus) {
this.id = id;
this.name = name;
this.joindata = joindata;
this.salary = salary;
this.bonus = bonus;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJoindata() {
return joindata;
}
public void setJoindata(String joindata) {
this.joindata = joindata;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
@Override
public String toString() {
return "Worker{" +
"id=" + id +
", name='" + name + '\'' +
", joindata='" + joindata + '\'' +
", salary=" + salary +
", bonus=" + bonus +
'}';
}
}
该类有id等等属性 重写了 tostring 方法
测试:
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Connection con = com.学习.优化方案1.Demo.getConnection();
// 注册
Class.forName("com.mysql.jdbc.Driver");
// 连接
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
Connection con = DriverManager.getConnection(url, username, passwd);
// 获取执行者对象
Statement statement = con.createStatement();
// 编写sql
String sql = "select * from work";
// 执行sql
ResultSet rs = statement.executeQuery(sql);
ArrayList<Worker> list = new ArrayList<>();
// 遍历 rs.next() 是否又下一行数据 返回布尔值
while (rs.next()){
// 获取每行 每个数据 数据库设计的什么类型 就要什么类型
int id = rs.getInt("id");
String name = rs.getString("ename");
String joindata = rs.getString("joindata");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
// 封装成新的对象
Worker worker = new Worker(id, name, joindata, salary, bonus);
list.add(worker);
}
// 遍历集合打印
for (Worker worker : list) {
System.out.println(worker);
}
con.close();
}
}
该方法返回的是set集合
最后执行结果:
// 获取执行者对象 Statement statement = con.createStatement();
通过 statement 调用相关方法 执行sql语句
5.优化数据库连接
综上所看,我们每次要执行一个语句 就要连接一次 ,代码重复 ,所以优化他!
5.1优化方案1: 封装成方法
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
* 封装 一个工具类
* */
public class ConnectionUtils {
// 定义一个方法 来获取连接 返回值类型 Connection 类型
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
// ip 端口号 连接库名
// ?useSSL=false 把警告去掉
String url = "jdbc:mysql://127.0.0.1:3306/java19?useSSL=false";
String username = "root";
String passwd = "root";
Connection con = DriverManager.getConnection(url, username, passwd);
return con;
}
}
5.2优化方案2:写成配置文件 *****
写一个properties文件 相关操作
Java之Properties集合_華同学.的博客-CSDN博客
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionUtils1 {
public static Connection getConnection1() throws IOException, ClassNotFoundException, SQLException {
// 读取配置文件里的信息
ClassLoader classLoader = ConnectionUtils1.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("cons.properties");
// 将文件信息 加载到 properties集合中
Properties pp = new Properties();
pp.load(is);
// 获取里面的信息
String classname = pp.getProperty("classname");
// 注册
Class.forName(classname);
// 获取 url 用户名 和 密码
String url = pp.getProperty("url");
String name = pp.getProperty("username");
String passwd = pp.getProperty("passwd");
// 连接
Connection con = DriverManager.getConnection(url, name, passwd);
return con;
}
}
测试:
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Text {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
// 测试读取文件
Connection con1 = ConnectionUtils1.getConnection1();
// 编写sql语句 删除
// String sql = "delete from work where id = 10";
String sql = "insert into work(ename,joindata,salary,bonus) values('小华','2002-02-02',10000,20)";
Statement statement = con1.createStatement();
int i = statement.executeUpdate(sql);
System.out.println(i);
}
}
6.sql 注入问题
下面我们有 user表
我们编写程序,来查找张三,故意把张三的密码写错。看看能不能查到
public class Demo {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
Connection con = ConnectionUtils1.getConnection1();
// 编写sql 查询
// String username = "张三";
// String passwd = "1234";//这里密码错误
String sql = "select * from user where username = '张三' and passwd = '1234' or '1' = '1'";
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
ArrayList<User> list = new ArrayList<>();
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("username");
String passwd1 = rs.getString("passwd");
User user = new User(id, name, passwd1);
list.add(user);
}
for (User user : list) {
System.out.println(user);
}
}
}
运行结果:
可以看到,我们只在后面拼接了一个 or '1' = '1' 就可以查出 所有信息。
从上面语句可以看出条件
username = '张三' and password = '1234'
不管是否满足,而or
后面的'1' = '1'
是始终满足的,最终条件是成立的,就可以正常的进行查询和登陆了。
1.PreparedStatement概述
PreparedStatement作用:
-
预编译SQL语句并执行:预防SQL注入问题
// SQL语句中的参数值,使用?占位符替代
String sql = "select * from user where username = ? and password = ?";
// 通过Connection对象获取,并传入对应的sql语句
PreparedStatement pstmt = con.prepareStatement(sql);
修改之后的代码:
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
Connection con = ConnectionUtils1.getConnection1();
// 编写sql 查询
// String username = "张三";
// String passwd = "1234";//这里密码错误
String sql = "select * from user where username = ? and passwd = ?";
// Statement statement = con.createStatement();
PreparedStatement ps = con.prepareStatement(sql);
// 设置值
ps.setString(1,"张三");
ps.setString(2,"123");
ResultSet rs = ps.executeQuery();
// ResultSet rs = statement.executeQuery(sql);
ArrayList<User> list = new ArrayList<>();
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("username");
String passwd1 = rs.getString("passwd");
User user = new User(id, name, passwd1);
list.add(user);
}
for (User user : list) {
System.out.println(user);
}
}
}
PreparedStatement原理
Java代码操作数据库流程如图所示:
-
将sql语句发送到MySQL服务器端
-
MySQL服务端会对sql语句进行如下操作
-
检查SQL语句
检查SQL语句的语法是否正确。
-
编译SQL语句。将SQL语句编译成可执行的函数。
检查SQL和编译SQL花费的时间比执行SQL的时间还要长。如果我们只是重新设置参数,那么检查SQL语句和编译SQL语句将不需要重复执行。这样就提高了性能。
-
执行SQL语句
-
7.数据库连接池
7.1简介:
数据库连接池是个容器,负责分配、管理数据库连接(Connection)
它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏
好处
资源重用
提升系统响应速度
避免数据库连接遗漏
之前我们代码中使用连接是没有使用都创建一个Connection对象,使用完毕就会将其销毁。这样重复创建销毁的过程是特别耗费计算机的性能的及消耗时间的。
而数据库使用了数据库连接池后,就能达到Connection对象的复用
连接池是在一开始就创建好了一些连接(Connection)对象存储起来。用户需要连接数据库时,不需要自己创建连接,而只需要从连接池中获取一个连接进行使用,使用完毕后再将连接对象归还给连接池;这样就可以起到资源重用,也节省了频繁创建连接销毁连接所花费的时间,从而提升了系统响应的速度。
7.2数据库连接池实现
-
标准接口:==DataSource==
官方(SUN) 提供的数据库连接池标准接口,由第三方组织实现此接口。该接口提供了获取连接的功能:
Connection getConnection()
那么以后就不需要通过
DriverManager
对象获取Connection
对象,而是通过连接池(DataSource)获取Connection
对象。 -
常见的数据库连接池
-
DBCP
-
C3P0
-
Druid
我们现在使用更多的是Druid,它的性能比其他两个会好一些。
-
-
Druid(德鲁伊)
-
Druid连接池是阿里巴巴开源的数据库连接池项目
-
功能强大,性能优秀,是Java语言最好的数据库连接池之一
-
7.3 Druid使用:
1.导入jar包
2.创建druid.properties
配置内容
driverClassName=com.mysql.jdbc.Driver #url=jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true url=jdbc:mysql://127.0.0.1:3306/java19?useSSL=false&useServerPrepStmts=true username=root password=root # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
public class DruidDemo {
public static void main(String[] args) throws Exception {
//1.导入jar包
//2.定义配置文件
//3. 加载配置文件
Properties pp = new Properties();
pp.load(new FileInputStream("jdbc连接数据库\\src\\druid.properties"));
//4. 获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
//5. 获取数据库连接 Connection
Connection con = dataSource.getConnection();
//获取到了连接后就可以继续做其他操作了
System.out.println(con);
}
}
连接成功!!
8.案例
需求:
完成商品品牌数据的增删改查操作
-
查询:查询所有数据
-
添加:添加品牌
-
修改:根据id修改
-
删除:根据id删除
环境准备:
1.数据库表 tb_brand
2.实体类 Brand
/*
*在实体类中,基本数据类型建议使用其对应的包装类型
* */
public class Brand {
private Integer id;
private String brand_name;
private String company_name;
private Integer ordered;
private String description;
private Integer status;
public Brand() {
}
public Brand(Integer id, String brand_name, String company_name, Integer ordered, String description, Integer status) {
this.id = id;
this.brand_name = brand_name;
this.company_name = company_name;
this.ordered = ordered;
this.description = description;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
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 +
", brand_name='" + brand_name + '\'' +
", company_name='" + company_name + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
8.1查看数据
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws Exception {
// 调用方法 遍历
ArrayList<Brand> brands = addListBrand();
for (Brand brand : brands) {
System.out.println(brand);
}
}
// 获取连接池方法
public static Connection getConnection() throws Exception {
Properties pp = new Properties();
pp.load(new FileInputStream("jdbc连接数据库\\src\\druid.properties"));
// 获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
// 获取数据库连接
Connection con = dataSource.getConnection();
return con;
}
// 查看所有
public static ArrayList<Brand> addListBrand() throws Exception {
ArrayList<Brand> list = new ArrayList<>();
Connection con = getConnection();
// 编写sql
String sql = "select * from tb_brand";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
int id = rs.getInt("id");
String brand_name = rs.getString("brand_name");
String company_name = rs.getString("company_name");
int ordered = rs.getInt("ordered");
String description = rs.getString("description");
int status = rs.getInt("status");
Brand brand = new Brand(id, brand_name, company_name, ordered, description, status);
list.add(brand);
}
return list;
}
}
8.2添加数据
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws Exception {
boolean b = insertDataBases();
if(b){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
}
// 为了多练习 先创建 数据库连接池
public static Connection getConnection1() throws Exception {
Properties pp = new Properties();
pp.load(new FileInputStream("jdbc连接数据库\\src\\druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
Connection con = dataSource.getConnection();
return con;
}
// 新增数据
public static boolean insertDataBases() throws Exception {
Connection con = getConnection1();
// String sql = "insert into tb_brand(brand_name,company_name,ordered,description,status) values()";
// 接收页面提供的参数
String brandName = "香飘飘";
String companyName = "香飘飘有限公司";
int ordered = 1;
String description = "飘地球一圈";
int status = 1;
String sql = "insert into tb_brand(brand_name,company_name,ordered,description,status) values(?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,brandName);
ps.setString(2,companyName);
ps.setInt(3,ordered);
ps.setString(4,description);
ps.setInt(5,status);
// 执行sql
int i = ps.executeUpdate();//受影响的行数
if(i > 0){
return true;
}
return false;
}
}
8.3修改数据
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws Exception {
boolean updatadatabase = updatadatabase();
if(updatadatabase){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}
public static Connection getConnection1() throws Exception {
Properties pp = new Properties();
pp.load(new FileInputStream("jdbc连接数据库\\src\\druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
Connection con = dataSource.getConnection();
return con;
}
// 修改
public static boolean updatadatabase() throws Exception {
Connection con = getConnection1();
// 获取数据 要修改
String brandname = "香飘飘";
String company_name = "香飘飘有限公司";
int ordered = 4;
String description = "飘到天上去!";
int status = 0;
String sql = "update tb_brand set brand_name = ?,company_name = ?,ordered = ?,description = ?,status = ? where brand_name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,brandname);
ps.setString(2,company_name);
ps.setInt(3,ordered);
ps.setString(4,description);
ps.setInt(5,status);
ps.setString(6,brandname);
int i = ps.executeUpdate();
con.close();
if(i>0){
return true;
}
return false;
}
}
8.4删除数据
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Properties;
public class Demo {
public static void main(String[] args) throws Exception {
boolean b = deleteDatabase();
if(b){
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
}
public static Connection getConnection2() throws Exception {
Properties pp = new Properties();
pp.load(new FileInputStream("jdbc连接数据库\\src\\druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(pp);
Connection con = dataSource.getConnection();
return con;
}
public static boolean deleteDatabase() throws Exception {
Connection con = getConnection2();
// 删除
String brandname = "小米";
String sql = "delete from tb_brand where brand_name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,brandname);
int i = ps.executeUpdate();
con.close();
if (i > 0){
return true;
}
return false;
}
}
为了多练习,我把获取连接 多写两遍