了解使用Java语言操作数据库的API之JDBC

一、简单了解

JDBC是官方定义的一套使用Java语言操作数据库的API,各数据库厂商按照此标准定义各自的实现类,因此在使用JDBC操作不同的数据库时,需导入对应的驱动 jar 包。

二、JDBC快速入门

步骤:

0. 创建工程,导入驱动jar包,一般放在根目录下的lib文件夹里。右击jar包,Add as Library。
1. 注册驱动
   Class,forName("com.mysql.jdbc.Driver"); // 有异常则抛出异常即可,这行代码也可上略不写
2. 获取连接
   String url = "jdbc:mysql://127.0.0.1:3306/mydbName?useSSL=false"; // 不使用useSSL连接
   String username = "root";
   String password = "123456";
   DriverManager.getConnection(url,username,password);
3. 定义sql语句
   String sql = "update table set name = 'xm' where id = 1";
4. 获取执行sql的Statement对象
   Statement stmt = conn.createStatement();
5. 执行sql
   int n = stmt.executeUpdate(sql); // 返回影响行数
6. 处理结果
   System.out.println(n);
7. 释放资源
   stmt.close();
   conn.close();

三、API 详解

1. DriverManager

驱动管理类,作用:1. 注册驱动 2. 获取数据库连接

2. Connection

数据库连接对象,作用:1. 获取执行 SQL 的对象 2. 管理事务

-- 开启事务
setAutoCommit(boolean); --  true 为自动提交,即关闭事务,反之开启事务。
-- 提交事务
commit();
-- 回滚事务
rollback();

-- 例子
--1. 注册驱动
   Class,forName("com.mysql.jdbc.Driver"); // 有异常则抛出异常即可,这行代码也可上略不写
--2. 获取连接
   String url = "jdbc:mysql://127.0.0.1:3306/mydbName?useSSL=false"; // 不使用useSSL连接
   String username = "root";
   String password = "123456";
   DriverManager.getConnection(url,username,password);
--3. 定义sql语句
   String sql1 = "update table set money = 2500 where id = 1";
   String sql2 = "update table set money = 1500 where id = 2";
--4. 获取执行sql的Statement对象
   Statement stmt = conn.createStatement();
--5. 执行sql
   -- 捕捉异常
   try {
      // 开启事务
      conn.setAutoCommit(false);
      
      int n1 = stmt.executeUpdate(sql1); // 返回影响行数
      --6. 处理结果
      System.out.println(n1);
      int n2 = stmt.executeUpdate(sql2); // 返回影响行数
      --6. 处理结果
      System.out.println(2);
      
      // 提交事务
      conn.commit();
   } catch (Exception throwables) {
        // 回滚事务
        conn.rollback();
        throwables.printStackTrace();
   } 
--7. 释放资源
   stmt.close();
   conn.close();

3. Statement

作用:执行 SQL 语句

executeUpdate(sql); // 执行 DML、DDL语句,DML返回影响行数,DDL执行成功也可能返回0

executeQuery(sql); // 执行 DQL 语句,返回 ResultSet结果集对象

4. ResultSet

结果集对象,封装了执行DQL返回结果

// 实体类person.java
package com.zrh.pojo;

public class Person {
    private int id;
    private String name;
    private double money;
    
    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 double getMoney() {
        return money;
    }
    public void setMoney(double id) {
        this.money = money;
    }
    
    @Override
    public String toString() {
        return "Person{" +
            "id=" + id +
            ",name=" + name + '\' +
            ",money=" + money +
            '}';
    }
}


// 测试类 test.java
public void testselectallo throws Exception{
// 1. 注册驱动
   Class,forName("com.mysql.jdbc.Driver"); // 有异常则抛出异常即可,这行代码也可上略不写
// 2. 获取连接
   String url = "jdbc:mysql://127.0.0.1:3306/mydbName?useSSL=false"; // 不使用useSSL连接
   String username = "root";
   String password = "123456";
   DriverManager.getConnection(url,username,password);
// 3. 定义sql语句
   String sql = "select * from table";
// 4. 获取执行sql的Statement对象
   Statement stmt = conn.createStatement();
// 5. 执行sql,接收结果
   ResultSet rs = stmt.executeQuery(sql); 
// 6. 处理结果
   List<Person> personList = new ArrayList();
   // rs.next()判断当前行是否有数据
   while (rs.next()){
      Person p = new Persoon(); 
       
      int id = rs.getInt(1);// 1 表述数据库表的第一列,也可写列的名称 "id"
      String name = rs.getString(2);
      double money = rs.getDouble(3);
      
      p.setId(id);
      p.setName(name);
      p.setMoney(money);
      
      personList.add(p);
   }
// 7. 释放资源
   rs.close(); // 要释放
   stmt.close();
   conn.close();
}

5. PreparedStatement

(1) Statement 存在 sql 注入风险

String name = "jddj";
String pwd = "'or '1' ='1";

String sql = "select * from table where username = '"+name+"' and password = '"+pwd+"'";

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 变成 select * from table where username = 'jddj' and password = ‘’ or 1 = 1

(2) PreparedStatement 解决 sql 注入问题

String name = "zs";
String pwd = "123456";

1. 传入 sql 语句,获取 PreparedStatement 对象。?占位符
String sql = "select * from table where username = ? and password ?";
PreparedStatement pstmt = conn.preparedStatement(sql);

2. 设置参数
pstmt.setString(1,name);
pstmt.setString(2,pwd); // 密码 'or '1' ='1 会变成真正的 'or '1' ='1, ‘会被转义成真的‘

3. 执行sql
ResultSet rs = pstmt.executeQuery(); // 不需传sql

四、数据库连接池

作用:不用每次执行sql都注册一个连接对象

官方标准接口:DataSource

第三方组织实现的接口之一:Druid (德鲁伊),阿里巴巴开源项目

Druid (德鲁伊)使用步骤

// 1. 导入 Druid 的 jar 包,记得 Add as...

// 2. 配置,建立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

// 3. 加载配置文件
Properties prop =new Properties();
prop.load(new FileInputstream(name:"src/druid.properties")); // 注意路径

// 4.获取连接池对象
DataSource dataSource=DruidDataSourceFactorycreateDataSource(prop);

//5.获取数据库连接Connection
Connection connection=dataSourcegetConnection();

System.outprintln(connection);

五、综合案例

1. 环境准备

创建数据库表 tb_brand 

创建实体类 Brand (参照上: 三、4)

2.  查询数据

/**
 * 查询所有数据
 * 1.sql:select * from tb_brand;
 * 2.参数:不需
 * 3.结果:List<Brand>
 */

@Test
public void getAllData throws Exception{
  // 1. 加载配置文件
  Properties prop =new Properties();
  propload(new FileInputStream(name:"jdbc-demo/src/druid.properties")); 
    
  // 2.获取连接池对象
  DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

  // 3.获取数据库连接Connection
  Connection conn = dataSource.getConnection()

  // 4.定义SQL
  String sql = "select * from tb_brand;";

  // 5.获取pstmt对象
  PreparedStatement pstmt=conn.prepareStatement(sql);

  // 6.设置参数
    
  // 7.执行sql
  ResultSet rs = pstmt.executeQuery();
    
  // 8.处理结果(参照:三、4)
      //获取数据
      //封装对象
      //封装集合
    
  // 9.释放资源
  rs.close(); // 要释放
  stmt.close();
  conn.close();
}

3. 添加数据

/**
 * 添加
 * 1.sql: insert into tb_brand(name,mark,...) values(?,?,...);
 * 2.参数:除id不用,其他所有均需
 * 3.结果:boolean
 */

@Test
public void add throws Exception{
    // 模拟前端提交的数据
    String name = "suibian";
    String mark = "随便";
    String city = "广州";
    
    // 1. 加载配置文件
    Properties prop =new Properties();
    propload(new FileInputStream(name:"jdbc-demo/src/druid.properties")); 
    
    // 2.获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

    // 3.获取数据库连接Connection
    Connection conn = dataSource.getConnection()

    // 4.定义SQL
    String sql = "insert into tb_brand(name,mark,city) values(?,?,?)";

    // 5.获取pstmt对象
    PreparedStatement pstmt=conn.prepareStatement(sql);

    // 6.设置参数
    pstmt.setString(1,name);
    pstmt.setString(2,mark);
    pstmt.setString(3,city);
    
    // 7.执行sql
    int n = pstmt.executeUpdate();
    
    // 8.处理结果
    if(n>0) {
        
    }
    
    // 9.释放资源
    stmt.close();
    conn.close();
}

4. 修改数据

/**
 * 修改
 * 1.sql: update tb_brand set (name = ?,mark = ?,city = ?) where id = ?;
 * 2.参数:Brand对象数据
 * 3.结果:boolean
 */

@Test
public void update throws Exception{
    // 模拟前端提交的数据
    int id = 2;
    String name = "suibian";
    String mark = "随便";
    String city = "广州";
    
    // 1. 加载配置文件
    Properties prop =new Properties();
    propload(new FileInputStream(name:"jdbc-demo/src/druid.properties")); 
    
    // 2.获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

    // 3.获取数据库连接Connection
    Connection conn = dataSource.getConnection()

    // 4.定义SQL
    String sql = "update tb_brand set (name = ?,mark = ?,city = ?) where id = ?";

    // 5.获取pstmt对象
    PreparedStatement pstmt=conn.prepareStatement(sql);

    // 6.设置参数
    
    pstmt.setString(1,name);
    pstmt.setString(2,mark);
    pstmt.setString(3,city);
    pstmt.setString(4,id);
    
    // 7.执行sql
    int n = pstmt.executeUpdate();
    
    // 8.处理结果
    if(n>0) {
        
    }
    
    // 9.释放资源
    stmt.close();
    conn.close();
}

5. 删除数据

/**
 * 修改
 * 1.sql: delete from tb_brand where id = ?;
 * 2.参数:Brand对象数据
 * 3.结果:boolean
 */

@Test
public void deleteById throws Exception{
    // 模拟前端提交的数据
    int id = 2;
    String name = "suibian";
    String mark = "随便";
    String city = "广州";
    
    // 1. 加载配置文件
    Properties prop =new Properties();
    propload(new FileInputStream(name:"jdbc-demo/src/druid.properties")); 
    
    // 2.获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);

    // 3.获取数据库连接Connection
    Connection conn = dataSource.getConnection()

    // 4.定义SQL
    String sql = "delete from tb_brand where id = ?";

    // 5.获取pstmt对象
    PreparedStatement pstmt=conn.prepareStatement(sql);

    // 6.设置参数
    
    pstmt.setString(1,name);
    pstmt.setString(2,mark);
    pstmt.setString(3,city);
    pstmt.setString(4,id);
    
    // 7.执行sql
    int n = pstmt.executeUpdate();
    
    // 8.处理结果
    if(n>0) {
        
    }
    
    // 9.释放资源
    stmt.close();
    conn.close();
}

 

posted @ 2022-08-16 17:44  RHCHIK  阅读(86)  评论(0编辑  收藏  举报