JDBC和连接池详细介绍

JDBC和连接池

JDBC基本介绍
  1. JDBC为访问不同的数据库提供了统一的接口

    为使用者屏蔽了细节问题。

  2. Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。

  3. JDBC原理图

  1. JDBC程序编写步骤

1.注册驱动 - 加载Driver类

2.获取连接 - 得到Connnection

3.执行增删改查 - 发送SQL 给mysql 执行

4.释放资源 - 关闭相关连接

//1.注册驱动
Driver driver = new Driver();   //这里有个小坑:mysql8.0版本,新建Driver对象时,选择com.mysql.cj.jdbc.   
//2.得到连接
String url = "jdbc:mysql://localhost:3306/db02?serverTimezone=UTC";
Properties properties = new Properties();
//注: user 和 password 是规定好的,不能改变
properties.setProperty("user","root");  //用户
properties.setProperty("password","root"); //密码
Connection connect = driver.connect(url, properties);
//3.执行sql语句
String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql);   //如果是DML语句,返回受影响的行数

System.out.println(rows > 0 ? "成功" : "失败");
//4.关闭资源
statement.close();
connect.close();
获取数据库连接的不同方式
使用反射加载Driver
//使用反射加载Driver
Class<?> aClass = Class.forName("con.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/db02";
String user = "root";
String password = "root";
DriverManager.registerDriver(driver); //注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第三章方式=" + connection);
使用Class.forName 自动完成注册驱动,简化代码
//使用反射加载Driver类,动态加载,更加灵活,价绍依赖性
Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db02";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
使用配置文件,让连接mysql更加灵活
//通过properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
ResultSet结果集
基本介绍
  1. 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成。
  2. ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
  3. next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集。
while(resultSet.next()) {//让光标向后移动,如果没有更多行,则返回false
    int id = resultSet.getInt(1);  //该行第一列
    String name = resultSet.getNString(2);  //该行第二列
    String sex = resultSet.getNString(3);  //3
    Date date =  resultSet.getDate(4);
    String phone = resultSet.getString(5);
    System.out.println(id + "\t" +name + "\t" + sex + "\t" + date + "\t" + phone);
}
Statement
基本介绍
  1. Statement对象 用于指向静态SQL语句并返回其生成的结果的对象
  2. 在连接建立后,需要对数据库进行访问,指向命名或是SQL语句,可以通过
    • Statement [存在SQL注入]
    • PerparedStatement [预处理]
    • CallableStatement [存储过程]
  3. Statement对象指向SQL语句,存在SQL注入风险
  4. SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。
  5. 要防范SQL注入,只要用PrepareStatement(从Statement扩展而来) 取代Statement 就可以了
Scanner scanner = new Scanner(System.in);
//让用户输入管理员和密码
System.out.println("请输入账户:");
String admin_name = scanner.nextLine();  // 1 ' or
System.out.println("请输入密码:");       //or '1'= '1
String admin_pwd = scanner.nextLine();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
String sql = "select aname,pwd from admin where aname = '"+ admin_name+"' and pwd = '"+admin_pwd+"'";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if(resultSet.next()) {
    String aname = resultSet.getNString(1);
    String pwd = resultSet.getNString(2);
    System.out.println(aname + " " + pwd );

}else {
    System.out.println("登录失败");
}
resultSet.close();
statement.close();
connection.close();
PreparedStatement
基本介绍
  1. PreparedStatement 执行的SQL 语句中的参数用问号(?)来表示,调用PreparedStatement 对象的setXxx() 方法来设置这些参数.setXxx() 方法有两个参数,第一个参数是要设置的SQL语句中的参数的索引(从 1开始), 第二个设置的SQL 语句中的参数的值
  2. 调用executeQuery(), 返回 ResultSet 对象
  3. 调用 executeUpadte(): 执行更新,包括增、删、改
预处理的好处
  1. 不再使用 + 拼接sql语句,减少语法错误。
  2. 有效的解决了SQL注入问题
  3. 大大减少了编译次数,效率问题
		String sql = "select aname,pwd from admin where aname = ? and pwd = ?";  //?相当于占位符
        //获取PreparedStatement对象 实现了 PreparedStatement 接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //给?赋值
        preparedStatement.setString(1,admin_name);
        preparedStatement.setString(2,admin_pwd);
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()) {
            String aname = resultSet.getNString(1);
            String pwd = resultSet.getNString(2);
            System.out.println(aname + " " + pwd );

        }else {
            System.out.println("登录失败");
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();  
JdbcAPI总结

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LYNd2yvQ-1667889993277)(C:\Users\HUAWEI\AppData\Roaming\Typora\typora-user-images\image-20221106163044630.png)]

封装JDBDCUtils
public class JDBCUtils {
    //定义相关属性
    private static String user;
    private static String password;
    private static String url;
    private static String driver;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\mysql.properties"));
            //读取数据
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            url = properties.getProperty("url");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //连接数据库
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }
    //关闭相关资源
    /*
    * 1.ResultSet 结果集
    * 2.Statement 或者 PreparedStatement
    * 3.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 (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
JDBC——事务
基本介绍
  1. JDBC程序中当一个Connection 对象创建时,默认情况下是自动提交事务:每一次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
  2. JDBC程序中为了让多个SQL 语句作为一个整体执行,需要使用事务
  3. 调用Connection 的 setAutoCommit(false) 可以取消自动提交事务
  4. 在所有的SQL 语句都成功执行后,调用 commit(); 方法提交事务
  5. 在其中某个操作失败或出现异常时,调用rollback(); 方法回滚事务
    public void testDMl() throws SQLException {  //insert,update,delete
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            String sql = "update account set balance = balance - 100 where id = 1";
            String sql2 = "update account set balance = balance + 100 where id = 2";
            connection = JDBCUtils.getConnection(); //在默认情况下,connection对象是自动提交
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.executeUpdate();

            preparedStatement = connection.prepareStatement(sql2);
            //执行 
            preparedStatement.executeUpdate();
            //关闭资源
            JDBCUtils.close(null,preparedStatement,connection);
        } catch (SQLException e) {
            //这里可以进行回滚,既可以撤销执行的SQL
            assert connection != null;
            connection.rollback();  //默认回滚到事务开始的状态
            throw new RuntimeException(e);
        } finally {
            System.out.println("");
        }
    }
批处理
基本介绍
  1. 当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。

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

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

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

数据库连接池
基本介绍
  1. 预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池” 中取出一个,使用完毕之后再放回去
  2. 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个
  3. 当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中
数据库连接池种类
  1. JDBC 的数据库连接池使用 javax.sqlDataSource 来表示,DataSource只是一个接口,该接口通常由第三方提供实现
  2. C3P0 数据库连接池,速度相对较慢,稳定性不错 ( hibernate,spring)
  3. DBCP数据库连接池,速度相对c3p0较快,但不稳定
  4. Proxool数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点
  5. BoneCP 数据库连接池,速度快
  6. Druid(德鲁伊) 是阿里云提供的数据库连接池,集DBCP、C3P0、Proxool优点于一身的数据库连接池
德鲁伊连接池1
        Connection connection = JDBCUtilsByDruid.getConnection();
        String sql = "select * from actor  where id = 2";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //给占位符赋值
//        preparedStatement.setInt(1,1);
        ArrayList<Actor> list = new ArrayList<Actor>();  //创建ArrayList对象,存放actor对象

        //执行
        ResultSet resultSet = preparedStatement.executeQuery();
        //遍历该结果集
        if (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("aname");
            Date borndate = resultSet.getDate("borndate");
            String phone = resultSet.getString("phone");
            //把得到的resultSet 的记录封装到Actor对象中,放入list集合
            list.add(new Actor(id,name,borndate,phone));
        }
        System.out.println("list集合数据="+ list);
        //关闭资源
        JDBCUtilsByDruid.close(null,preparedStatement,connection);
德鲁伊连接池2
public class JDBCUtils {
    private static final DruidDataSource dataSource;
    static {
        // 读取jdbc.properties属性配置文件
        try {
            Properties properties = new Properties();
            //创建 数据库连接池
            properties.load(new FileInputStream("src//jdbc.properties"));
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接池中的连接
     * @return 如果返回null说明获取连接失败
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void main(String[] args) {

    }

    /**
     * 放回数据库连接池
     * @param connection
     * @throws SQLException
     */
    public static void close(Connection connection) {
        if(connection!= null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
配置文件

username=xxxxx
password=xxxxx
url=jdbc:mysql://localhost:3306/book
driverClassName=com.mysql.cj.jdbc.Driver
initialSize=5
maxActive=10
Apache——DBUtils
基本介绍

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

DbUtils类

1.QueryRunner类:该类封装了SQL的执行,是线程安全的。可以实现增删改查批处理
2.使用QueryRunner类实现查询
3.ResultSetHandler接口:该接口用于处理java.sql.ResultSet,将数据按要求转换为另一种形式。

DAO和增删改查
基本说明

1.DAO: date access object数据访问对象
2.BasicDao 基础上,实现一张表 对应一个Dao, 更好的完成功能,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值