JDBC-2(CRUD)

3.PreparedStatement实现CRUD

image

3.1 操作和访问数据库

  • 数据库连接被用于向数据库服务器发送命令和SQL语句,接受数据库服务器返回的结果。(一个数据库连接就是也给Socket连接)

  • 在 java.sql 包中有 3 个接口分别定义了对数据库的调用的不同方式:

    • Statement:用于执行静态 SQL 语句并返回它所生成结果的对象。
    • PrepatedStatement:SQL 语句被预编译并存储在此对象中,可以使用此对象多次高效!地执行该语句。
    • CallableStatement:用于执行 SQL 存储过程

image

3.2 Statement操作数据表的弊端

  1. 存在拼串操作,繁琐
  2. 存在SQL注入问题 SELECT user, password FROM user_table WHERE user='a' OR 1 = ' AND password = ' OR '1' = '1'
    • SQL注入是利用某些系统没有对用户输入的数据进行充分检查,而在用户输入数据中注入非法的SQL语句段或命令,从而利用系统的SQL引擎完成恶意行为的做法。

3.3 PreparedStatement的使用

3.3.1 PreparedStatement介绍

  • 可以通过调用 Connection 对象的 preparedStatement(String sql) 方法获取 PreparedStatement 对象

  • PreparedStatement 接口是 Statement 的子接口,它表示一条预编译过的 SQL 语句

  • PreparedStatement 对象所代表的 SQL 语句中的参数用问号(?)来表示,调用 PreparedStatement 对象的 setXxx() 方法来设置这些参数. setXxx() 方法有两个参数,第一个参数是要设置的 SQL 语句中的参数的索引(从 1 开始),第二个是设置的 SQL 语句中的参数的值

3.3.2 PreparedStatement vs Statement

  • 代码的可读性和可维护性。

  • PreparedStatement 能最大可能提高性能:

    • DBServer会对预编译语句提供性能优化。因为预编译语句有可能被重复调用,所以语句在被DBServer的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行。
    • 在statement语句中,即使是相同操作但因为数据内容不一样,所以整个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存。这样每执行一次都要对传入的语句编译一次。
    • (语法检查,语义检查,翻译成二进制命令,缓存)
  • PreparedStatement 可以防止 SQL 注入

3.3.3 Java与SQL对应数据类型转换表

image

使用步骤:

  1. 建立数据库连接
  2. 预编译sql语句,返回PreparedStatement实例
  3. 填充占位符(注意: 与数据库交互的API起始值为1)
  4. 执行sql操作
  5. 关闭资源(connection preparedStatement)

3.3.4 增删改

点击查看代码
    @Test //向t_account中添加一条记录
    public void Update1() throws Exception{
        //1.获取配置文件基本信息
        InputStream inputStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        prop.load(inputStream);

        String url = prop.getProperty("url");
        String driverClass = prop.getProperty("driverClass");
        String user = prop.getProperty("user");
        String password = prop.getProperty("password");

        //2.加载驱动
        Class.forName(driverClass);

        //3,获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        //4.update,预编译sql语句,返回PreparedStatement实例
        String sql = "insert into t_account(username, money) values(?,?)";//?为占位符
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //5.填充占位符(与数据库交互的API起始值为1)
        preparedStatement.setString(1, "Mike");
        preparedStatement.setInt(2, 1000000);

        //6.执行sql操作
        preparedStatement.execute();

        //7.资源关闭(连接和preparedStatement都要关)
        preparedStatement.close();
        connection.close();
    }

进阶:封装connection与close的实现

点击查看封装类JDBCUtils
public class JDBCUtils {
    public static Connection getConnection() throws Exception{
        //1.获取配置文件基本信息
        InputStream inputStream = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        prop.load(inputStream);

        String url = prop.getProperty("url");
        String driverClass = prop.getProperty("driverClass");
        String user = prop.getProperty("user");
        String password = prop.getProperty("password");

        //2.加载驱动
        Class.forName(driverClass);

        //3,获取连接
        Connection connection = DriverManager.getConnection(url, user, password);

        return connection;
    }

    public static void closeResource(Connection connection, PreparedStatement preparedStatement){
        try{
            if(connection != null) connection.close();
            if(preparedStatement != null) preparedStatement.close();
        } catch (SQLException e){
            e.printStackTrace();
        }

    }
}
点击查看实现类
    @Test
    public void Update2() throws Exception {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {

            //1.获取连接
            connection = JDBCUtils.getConnection();

            //2.预编译sql语句,返回preparedStatement实例
            String sql = "UPDATE t_account\n" +
                    "SET money = ?\n" +
                    "WHERE username = ?;";
            preparedStatement = connection.prepareStatement(sql);


            //可选 填充占位符
            preparedStatement.setInt(1, 200000000);
            preparedStatement.setString(2, "Jingd");

            //3执行sql操作
            preparedStatement.execute();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //4.资源关闭
            JDBCUtils.closeResource(connection, preparedStatement);
        }
    }

进阶:通用增删改操作(函数传参为sql语句与占位符)

点击查看代码
    public void allUpdate(String sql, Object ...args){
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            //1.建立连接
            connection = JDBCUtils.getConnection();

            //2.预编译sql语句,返回preparedStatement实例
            preparedStatement = connection.prepareStatement(sql);

            //3.(可选) 填充占位符
            for (int i = 0; i << args.length; i++) {
                //注意! 易错!
                preparedStatement.setObject(i + 1, args[i]);
            }

            //4.执行
            preparedStatement.execute();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            //5.关闭资源
            JDBCUtils.closeResource(connection, preparedStatement);
        }
    }

注:若表中有关键词名与sql语句名重名,可用着重号``表示独特性。


3.3.5 查

1-ResultSet概述

  • 查询需要调用PreparedStatement 的 executeQuery() 方法,查询结果是一个ResultSet 对象

  • ResultSet 对象以逻辑表格的形式封装了执行数据库操作的结果集,ResultSet 接口由数据库厂商提供实现

  • ResultSet 返回的实际上就是一张数据表。有一个指针指向数据表的第一条记录的前面。

  • ResultSet 对象维护了一个指向当前数据行的游标,初始的时候,游标在第一行之前,可以通过 ResultSet 对象的 next() 方法移动到下一行。调用 next()方法检测下一行是否有效。若有效,该方法返回 true,且指针下移。相当于Iterator对象的 hasNext() 和 next() 方法的结合体。

  • 当指针指向一行时, 可以通过调用 getXxx(int index) 或 getXxx(int columnName) 获取每一列的值。

    • 例如: getInt(1), getString("name")
    • 注意:Java与数据库交互涉及到的相关Java API中的索引都从1开始。
  • ResultSet 接口的常用方法:

    • boolean next()

    • getString()

image

2-ResultSetMetData

  • 可用于获取关于 ResultSet 对象中列的类型和属性信息的对象

  • ResultSetMetaData meta = rs.getMetaData();

    • getColumnName(int column):获取指定列的名称

    • getColumnLabel(int column):获取指定列的别名

    • getColumnCount():返回当前 ResultSet 对象中的列数。

    • getColumnTypeName(int column):检索指定列的数据库特定的类型名称。

    • getColumnDisplaySize(int column):指示指定列的最大标准宽度,以字符为单位。

    • isNullable(int column):指示指定列中的值是否可以为 null。

    • isAutoIncrement(int column):指示是否自动为指定列进行编号,这样这些列仍然是只读的。

image


查询操作

  • R与CUD的主要区别在于执行与处理结果,查询结果用FormatClass类
点击查看代码
    @Test 
    public void selectTest1(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //1.建立数据库连接
            connection = JDBCUtils.getConnection();

            //2.预编译sql语句,返回preparedStatement实例
            String sql = "SELECT *\n" +
                    "FROM t_account\n" +
                    "WHERE id IN(?,?);";
            preparedStatement = connection.prepareStatement(sql);

            //3.填充占位符
            preparedStatement.setObject(1, 1);
            preparedStatement.setObject(2, 2);

            //4.执行(区别于CRD的主要),并返回结果集
            resultSet = preparedStatement.executeQuery();

            //5.处理结果集****
            //next方法:判断结果集下一条是否有数据,若有返回true且指针下移;否则返回false
            while(resultSet.next()){
                //获取当前数据的各个字段值
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                int money = resultSet.getInt(3);
                Date date = resultSet.getDate(4);

                //1.sout 2.Object[]
                //3.将数据封装为一个对象(推荐)
                FormatClass formatClass = new FormatClass(id, name, money, date);
                System.out.println(formatClass);

            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
    }
点击查看ORM类
package Jing.bean;

import java.sql.Date;

//ORM编程思想(object relational mapping)
//一个数据对应一个java类
//表中的一条记录对应java类的一个对象
//表中的一个字段对应java类的一个属性
public class FormatClass {

    private int id;
    private String name;
    private int money;
    private Date birth;

    public FormatClass(int id, String name, int money, Date birth) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.birth = birth;
    }

    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 int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public String toString() {
        return "FormatClass{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", birth=" + birth +
                '}';
    }
}

进阶-通用查找操作(反射实现)

点击查看代码
    //针对查询的通用操作
    public List<FormatClass> selectAll(String sql, Object ...args){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //1.获取数据库链接
            connection = JDBCUtils.getConnection();

            //2.预编译sql语句,返回preparedStatement实例
            preparedStatement = connection.prepareStatement(sql);

            //3.填充占位符
            for(int i = 0; i < args.length; i++){ //>
                preparedStatement.setObject(i + 1, args[i]);
            }

            //4.执行-返回结果集
            resultSet = preparedStatement.executeQuery();

            //获取结果集的元数据(修饰现有数据的数据)
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int colCount = resultSetMetaData.getColumnCount(); //获取结果集的列数

            //5.处理结果集
            List<FormatClass> list = new ArrayList<>();
            while(resultSet.next()){
                FormatClass formatClass = new FormatClass();
                //处理一行结果集中数据的每一列
                for(int i = 1; i <= colCount; i++){  //>
                    //列值
                    Object colVal = resultSet.getObject(i);
                    //列名
                  //String colName = resultSetMetaData.getColumnName(i);

                    String colName = resultSetMetaData.getColumnLabel(i);
                    //给format对象指定的colName属性赋值为colValue - 反射
                    Field field = FormatClass.class.getDeclaredField(colName);//获取指定属性名
                    field.setAccessible(true);//设置为可访问
                    field.set(formatClass, colVal);
                }
//                int id = resultSet.getInt(1);
//                String username = resultSet.getString(2);
//                int money = resultSet.getInt(3);
//                Date date = resultSet.getDate(4);
                list.add(formatClass);
            }
            return list;

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

  1. ResultSetMetaData获取结果集元数据 -> 获取数据库结果集列名与结果集列数
    • 结果集ResultSet对应数据
    • 结果集元数据ResultSetMetaData对应修饰(列名、列数)
      • getColumnName() 获取结果集列名 (不推荐使用,缺乏普适性)
      • getColumnLabel() 获取列的别名 (没有起别名时就是类的列名)
      • 针对表的字段名与类的属性名不相同情况时,需使用类的属性名来命名字段别名
  2. 使用反射获取指定属性、将私有属性设置为可访问并填充值
    1. 获取属性
    2. 设置属性为可访问true
    3. 填充属性列值set

查询操作总结:

image


进阶-针对不同表的通用查询操作

点击查看代码
    //泛型方法,clazz为对应返回类
    public <T> List<T> getInstance(Class<T> clazz, String sql, Object ...args){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            //1.建立连接
            connection = JDBCUtils.getConnection();

            //2.预编译sql语句获取preparedStatement对象
            preparedStatement = connection.prepareStatement(sql);

            //3.填充占位符
            for(int i = 0; i < args.length; i++){
                preparedStatement.setObject(i + 1, args[i]);
            }

            //4.获取结果集与结果集元数据
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int countVal = resultSetMetaData.getColumnCount();

            //5.数据处理
            List<T> list = new ArrayList<>();
            while(resultSet.next()){
                T t = clazz.newInstance();
                for(int i = 0; i < countVal; i++){
                    //获取查询结果
                    Object Val = resultSet.getObject(i + 1);

                    //获取列名
                    String valName = resultSetMetaData.getColumnLabel(i + 1);

                    //反射注入
                    Field field = t.getClass().getDeclaredField(valName);
                    field.setAccessible(true); //设置私有属性可访问
                    field.set(t, Val);
                }
                list.add(t);
            }

            return list;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }
  • 使用泛型方法处理泛型类并返回对应泛型集合(传参时将类的类型传入xxx.class)

3.3.6 Blob类型操作

  • PreParedStatement可操作Blob数据实现其CRUD,且可实现更高效的批量操作
  • MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
  • 插入BLOB类型的数据必须使用PreparedStatement,因为BLOB类型的数据无法使用字符串拼接写的。
  • 实际使用中根据需要存入的数据大小定义不同的BLOB类型。
  • 需要注意的是:如果存储的文件过大,数据库的性能会下降。
  • 如果在指定了相关的Blob类型以后,还报错:xxx too large,那么在mysql的安装目录下,找my.ini文件加上如下的配置参数: max_allowed_packet=16M。同时注意:修改了my.ini文件之后,需要重新启动mysql服务。

MySQL的四种BLOB类型(除了在存储的最大信息量上不同外,他们是等同的)

image

操作方法

  1. 使用输入流传入Blob类型参数,输出流保存Blob数据于本地
  2. preparedStatement.setBlob()方式添加Blob型数据
  3. getBlob()方式获取Blob参数,且需将其转为流形式保存本地

1-添加

点击查看添加Blob数据示例
    @Test
    public void addBlob() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            String sql = "insert into t_book(userid, username, ustatus, photo) values(?,?,?,?);";
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);

            FileInputStream f = new FileInputStream(new File("timg.jpg"));

            preparedStatement.setObject(1, 22);
            preparedStatement.setObject(2, "hahaha");
            preparedStatement.setObject(3, "ddd");
            preparedStatement.setBlob(4, f);

            preparedStatement.execute();

        } catch (Exception e){
            e.printStackTrace();

        } finally {
            JDBCUtils.closeResource(connection, preparedStatement);

        }
    }

2-查看(保存本地)

点击查看代码
    public void selectBlob() throws Exception{
        Connection connection = JDBCUtils.getConnection();
        String sql = "SELECT photo FROM t_book WHERE userid = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setInt(1, 22);

        ResultSet resultSet = preparedStatement.executeQuery();

        if(resultSet.next()){
            //将blob以文件形式保存本地
            Blob blob = resultSet.getBlob(1);
            InputStream inputStream = blob.getBinaryStream();
            FileOutputStream fileOutputStream = new FileOutputStream("Kobe.jpg");
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer))  != -1){
                fileOutputStream.write(buffer, 0, len);
            }

            inputStream.close();
        }

        JDBCUtils.closeResource(connection, preparedStatement);
    }

3.3.7 批量插入

1-批量插入

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

  1. addBatch(String):添加需要批量处理的SQL语句或是参数;
  2. executeBatch():执行批量处理语句;
  3. clearBatch():清空缓存的数据
  • mysql服务器默认是关闭批处理的,我们需要通过一个参数,让mysql开启批处理的支持。
    • ?rewriteBatchedStatements=true 写在配置文件的url后面

2-自动提交

设置关闭MySQL自动提交connection.setAutoCommit(false);;数据批量插入完成之后再提交connection.commit();

3-实现代码

点击查看代码
    @Test
    public void batch1(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try{
            connection = JDBCUtils.getConnection();

            //设置不允许自动提交数据
            connection.setAutoCommit(false);

            String sql = "insert into goods(name) values(?)";
            preparedStatement = connection.prepareStatement(sql);

            for(int i = 1; i <= 100; i++){
                preparedStatement.setObject(1, "name" + i);
//                preparedStatement.execute();

                //1.攒sql
                preparedStatement.addBatch();

                //2.执行batch(以50次为界)
                if(i % 50 == 0){
                    //执行batch
                    preparedStatement.executeBatch();
                    //清空batch
                    preparedStatement.clearBatch();
                }

                //提交数据
                connection.commit();
            }
        } catch (Exception e){

        } finally {
            JDBCUtils.closeResource(connection, preparedStatement);
        }
    }

3.3.8 资源释放

  • 释放ResultSet, Statement,Connection。
  • 数据库连接(Connection)是非常稀有的资源,用完后必须马上释放,如果Connection不能及时正确的关闭将导致系统宕机。Connection的使用原则是尽量晚创建,尽量早的释放。
  • 可以在finally中关闭,保证及时其他代码出现异常,资源也一定能被关闭。
posted @ 2021-09-24 15:44  rttrti  阅读(45)  评论(0编辑  收藏  举报