Java基础——JDBC

JDBC

编写程序步骤

  1. 注册驱动——加载Driver类
  2. 获取连接——得到Connection
  3. 执行增删改查——发送SQL 给mysql执行
  4. 释放资源——关闭相关连接

快速入门

package JDBC;


import com.mysql.jdbc.Driver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

public class work01 {
    public static void main(String[] args) throws Exception{
        //1。注册驱动
        Driver driver = new Driver();//创建driver对象
        //2.得到连接
        //老师解读
        //(1) jdbc:mysql://规定好表示协议,通过jdbc的方式连接mysql
        //(2)localhost主机,可以是ip地址
        //(3)3306表示mysql监听的端口
        //(4)hsp_db02连接到mysql dbms的哪个数据库
        //(5)mysq的连接本质就是前面学过的socket连接
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        //将用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connect = driver.connect(url, properties);
        //3.执行sql
        String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";
        //statement用于执行静态SQL语句并返回其生成的结果的对象
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);
        //如果是 dml语句,返回的就是影响行数
        System.out.println(rows > 0?"成功":"失败");
        //4.关闭连接资源
        statement.close();
        connect.close();
    }
}

连接数据库的方式

package JDBC;

import com.mysql.jdbc.Driver;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class work02 {
    @Test
    public void collect01() throws Exception{
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver =(Driver)aClass.newInstance();
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }
    @Test
    public void collect02() throws Exception{
        Driver driver = new Driver();
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }
    @Test
    public void collect03() throws Exception{
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver =(Driver)aClass.newInstance();
        DriverManager.registerDriver(driver);
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connection = DriverManager.getConnection(url, properties);
        System.out.println(connection);
    }
    @Test
    public void collect04() throws Exception{
        //第三种方法的简化版
//        简化的代码
//        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
//        Driver driver =(Driver)aClass.newInstance();
//        DriverManager.registerDriver(driver);
        //可以简化的原因
        Class.forName("com.mysql.jdbc.Driver");
        //Driver的静态代码块会在类加载时try注册,所以不用自己在注册
//        static {
//            try {
//                DriverManager.registerDriver(new Driver());
//            } catch (SQLException var1) {
//                throw new RuntimeException("Can't register driver!");
//            }
//        }
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connection = DriverManager.getConnection(url, properties);
        System.out.println(connection);
    }
    @Test
    public void collect05() throws Exception{
        //mysqL驱动5.1.6可以无需CLass . forName("com.mysql.jdbc.Driver");
        //从jdk1.5以后使用了jdbc4,不再需要显示调用class.forName()注册驱动而是
        // 自动调用驱动jar包下META-INF\services\java .sql.Driver文本中的类名称去注册
        //建议还是写上CLass.forName("com.mysql.jdbc.Driver"),更加明确
//        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connection = DriverManager.getConnection(url, properties);
        System.out.println(connection);
    }

}

ResultSet结果集

基本介绍

  • 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
  • ResultSet对象保持一个光道指向当前的数据行,最初,光标位于第一行。
  • next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集

代码练习

package JDBC;


import com.mysql.jdbc.Driver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class work01 {
    public static void main(String[] args) throws Exception{
        //1。注册驱动
        Driver driver = new Driver();//创建driver对象
        //2.得到连接
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connect = driver.connect(url, properties);
        //3.执行sql
        String sql = "select * from actor; ";
        Statement statement = connect.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        //4.输出结果
        while (resultSet.next()){
            System.out.println(resultSet.getInt(1)+resultSet.getString(2)+resultSet.getString(3));
        }
        //5.关闭连接资源
        resultSet.close();
        statement.close();
        connect.close();
    }
}

Statement

基本介绍

  • Statement对象用于执行静态SQL语句并返回其生成的结果的对象
  • 在连接建立后,需要对数据库进行访问,执行命名或是SQL语句,可以通过
    • Statement[存在SQL注入]
    • PreparedStatement[预处理]
    • CallableStatement[存储过程]
  • Statement对象执行SQL语句,存在SQL注入风险
  • SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。
  • 要防范SQL注入,只要用 PreparedStatement(从Statement扩展而来)取代Statement就可以了

SQL注入

-- 正常语句
SELECT *
	FROM admin
	WHERE NAME= 'tom' AND pwd = '123';
-- sql注入
-- 输入用户名为   1' or
-- 输入密码为    or '1'= ' 1
SELECT *
	FROM admin
	WHERE NAME= '1' OR ' AND pwd = 'OR '1'= '1';

PreparedStatement

基本介绍
  • PreparedStatement 执行的SQL语句中的参数用问号(?)来表示,调用PreparedStatement 对象的setXxx()方法来设置这些参数. setXxx()方法有两个参数,第一个参数是要设置的SQL语句中的参数的索引(从1开始),弟二个是设置的SQL语句中的参数的值
  • 调用executeQuery),返回ResultSet 对象
  • 调用executeUpdate():执行更新,包括增、删、修改
预处理优点
  • 不再使用+拼接sql语句,减少语法错误
  • 有效的解决了sql注入问题!
  • 大大减少了编译次数,效率较高
代码练习
package JDBC;


import com.mysql.jdbc.Driver;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;

public class work01 {
    public static void main(String[] args) throws Exception{
        Scanner scanner = new Scanner(System.in);
        //1。注册驱动
        Driver driver = new Driver();//创建driver对象
        //2.得到连接
        String url="jdbc:mysql://localhost:3306/hello02?useUnicode=true&characterEncoding=utf-8";
        Properties properties = new Properties();
        properties.load(new BufferedReader(new FileReader("e:\\f1.properties")));
        Connection connect = driver.connect(url, properties);
        //3.执行sql
        String sql = "select * from actor where id=? and name=?; ";
        PreparedStatement preparedStatement = connect.prepareStatement(sql);
        preparedStatement.setString(1,"1");
        preparedStatement.setString(2,"刘德华");
        ResultSet resultSet = preparedStatement.executeQuery();
        //4.输出结果
        while (resultSet.next()){
            System.out.println(resultSet.getInt(1)+resultSet.getString(2)+resultSet.getString(3));
        }
        //5.关闭连接资源
        resultSet.close();
        preparedStatement.close();
        connect.close();
    }
}

JDBC_API_知识点总结

在这里插入图片描述

JDBC_utils

package JDBC;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBC_utils {
    private static String url;
    private static String user;
    private static String pwd;
    private static String driver;
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader("e:\\f1.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String user = properties.getProperty("user");
        String url = properties.getProperty("url");
        String pwd = properties.getProperty("pwd");
        String driver = properties.getProperty("driver");
    }
    public static Connection get_connection(){
        try {
            return DriverManager.getConnection(url,user,pwd);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables);
        }
    }
    public static void close_connection(ResultSet set, Statement sta,Connection connection){
        try {
            if (set != null) {
                set.close();
            }
            if (sta != null) {
                sta.close();
            }
            if (connection != null) {
                connection.close();
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

事务

基本介绍

  • JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个SQL 语句时,,如果执行成功,就会向数据库自动提交,而不能回滚。
  • JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
  • 调用Connection的 setAutoCommit(false)可以取消自动提交事务
  • 在所有的SQL语句都成功执行后,调用commit();方法提交事务
  • 在其中某个操作失败或出现异常时,调用rollback();方法回滚事务

批处理

基本介绍

  • 当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。

  • JDBC的批量处理语句包括下面方法:

    • addBatch(): 添加需要批量处理的SQL语句或参数
    • executeBatch(): 执行批量处理语句;
    • clearBatch(): 清空批处理包的语句
  • JDBC连接MySQL时,如果要使用批处理功能,请再url中加参数

    ?rewriteBatchedStatements=true

  • 批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高

数据库连接池

传统获取connection问题分析

  • 传统的JDBC数据库连接使用DriverManager 来获取,每次向数据库建立连接的时候都要将Connection 加载到内存中,再验证IP地址,用户名和密码(0.05s~1s时间)。需要数据库连接的时候,就向数据库要求一个,频繁的进行数据库连接操作将占用很多的系统资源,容易造成服务器崩溃。
  • 每一次数据库连接,使用完后都得断开,如果程序出现异常而未能关闭,将导致数据库内存泄漏,最终将导致重启数据库。
  • 传统获取连接的方式,不能控制创建的连接数量,如连接过多,也可能导致内存泄漏,MySQL崩溃。
  • 解决传统开发中的数据库连接问题,可以采用数据库连接池技术(connection pool)。

基本介绍

  • 预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。
  • 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个。
  • 当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中

示意图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uNdDFElz-1667830859084)(E:\自学路线\java基础\笔记\image-20221107185513713.png)]

分类

JDBC数据库连接池使用javax.sqI.DataSource来表示,DataSource只是一个接口,该接口通常由第三方提供实现

  • C3PO数据库连接池,速度相对较慢,稳定性不错(hibernate, spring)
  • DBCP数据库连接池,速度相对c3p0较快,但不稳定
  • Proxool数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点
  • BoneCP 数据库连接池,速度快
  • Druid(德鲁伊)是阿里提供的数据库连接池,集DBCP、C3PO、Proxool优点于一身的数据库连接池

C3PO的使用

package JDBC;

public class C3PO {
    public static void main(String[] args) {
        //第一种方式
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //给数据源comboPooledDataSource 设置相关的参数
        // 注意:连接管理是由 comboPooledDataSource 来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);
        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        comboPooledDataSource.setMaxPoolSize(50);
        //连接
        Connection connection = comboPooledDataSource.getConnection();
        //关闭
        connection.close();
        //第二种方式使用配置文件模板来完成
        //1。将c3p0提供的c3p0.config.xml拷贝到 src目录下
        // 2.该文件指定了连接数据库和连接池的相关参数
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("文件名");
        //连接
        Connection connection = comboPooledDataSource.getConnection();
        //关闭
        connection.close();
    }
}

Druid(德鲁伊)的使用

package JDBC;

import java.io.FileInputStream;

public class C3PO {
    public static void main(String[] args) {
        //1。加入 Druid jar包
        //2.加入配置文件 druid.properties,将该文件拷贝项目的src目录
        // 3.创建Properties对象,读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));
        //4.创建一个指定参数的数据库连接池,Druid连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        //连接
        Connection connection = dataSource.getConnection();
        //关闭
        connection.close();
    }
}

JDBC_utils(基于德鲁伊)

package JDBC;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBC_utils {
    private static DataSource ds;
    //在静态代码块完成ds初始化
    static {
        Properties properties = new Properties();try {
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    //编写getConnection方法
    public static Connection getConnection() throws SQLException
    {
        return ds.getConnection();
    }
    //关闭连接,老师再次强调:在数据库连接池技术中,close不是真的断掉连接//而是把使用的Connection对象放回连接池
    public static void close(ResultSet resultSet,Statement statement,Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

Apache-DBUtils

commons-dbutils是 Apache组织提供的一个开源JDBC工具类库,它是对JDBC的封装,使用dbutils能极大简化jdbc编码的工作量。

DbUtils类

  • QueryRunner类:该类封装了SQL的执行,是线程安全的。可以实现增、删、改、查、批处理使

  • QueryRunner类实现查询

  • ResultSetHandler接口:该接口用于处理java.sql.ResultSet,将数据按要求转换为另一种形式

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O7MeEFuF-1667830859085)(E:\自学路线\java基础\笔记\image-20221107200459010.png)]

代码演示

package JDBC;

public class ap {
    public static void main(String[] args) {
        Connection connection = JDBCUtilsByDruid.getConnection();
        //2.使用 DBUtils 类和接口,先引入DBUtils 相关的jar ,加入到本Project
        // 3.创建QueryRunner
        QueryRunner queryRunner = new QueryRunner();
        //4。就可以执行相关的方法,返回ArrayList结果集
        String sql = "select * from actor where id >= ?";
        //(1) query方法就是执行sql 语句,得到resultset ---封装到 -->ArrayList集合中
        //(2)返回集合
        //(3)connection:连接
        // (4) sql :执行的sql语句
        //(5) new BeanListHandler<>(Actor.class):在将resultset -> Actor对象->封装到 ArrayList
        // 底层使用反射机制去获取Actor 类的属性,然后进行封装
        //(6)1就是给 sql 语句中的?赋值,可以有多个值,因为是可变参数Object. .. params
        List<Actor> list =
        queryRunner.query(connection,sql, new BeanListHandler<>(Actor.class),1);
        System.out.println("输出集合的信息");
        for (Actor actor : list) {
            System.out.println(actor);
        }
        //释放资源
        JDBCUtilsByDruid.close();
    }
}

BasicDao

基本说明

  • DAO:data access object数据访问对象
  • 这样的通用类,称为BasicDao,是专门和数据库交互的,即完成对数据库(表)的crud操作。
  • 在BaiscDao的基础上,实现一张表对应一个Dao,更好的完成功能,比如 Customer表-Customer.java类(javabean)-CustomerDao.java

组成

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zcG7z0tI-1667830859086)(E:\自学路线\java基础\笔记\image-20221107203722888.png)]

BasicDao代码

package JDBC;

import java.sql.SQLException;

public class ap {
    private QueryRunner qr =new QueryRunner();
    //开发通用的dml方法,针对任意的表
    public int update(String sql, Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            int update = qr.update(connection, sql, parameters);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);//将编译异常->运行异常,抛出
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }
    public List<T> queryHMulti(String sql,Class<T> clazz,Object... parameters){
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection,sql, new BeanListHandler<T>(clazz),parameters);
        }catch (SQLException e) {
        throw new RuntimeException(e);//将编译异常->运行异常抛出
        }finally {
            JDBCUtilsByDruid.close(null, null,connection);
        }
        return null;
    }
    //查询单行结果的通用方法
    public T querySingle(String sql,Class<T> clazz,Object... parameters) {
        Connection connection = null;
        try {
            connection = JDBCUtilsByDruid.getConnection();
            return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);//将编译异常->运行异常,抛出
        } finally {
            JDBCUtilsByDruid.close(null, null, connection);
        }
    }
    //查询单行单列的方法,即返回单值的方法
    public Object queryScalar(String sql,Object... parameters){
            Connection connection = null;
            try{
                connection = JDBCUtilsByDruid.getConnection();
                return qr. query(connection,sql, new ScalarHandler(),parameters);
            }catch (SQLException e) {
                throw new RuntimeException(e);//将编译异常->运行异常抛出
                }finally{
                    JDBCUtilsByDruid.close(null, null,connection);
            }
        }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XZY-SUNSHINE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值