大数据必学Java基础(九十六):PreparedStatement完成CURD和批处理_世界聚看点

来源: 腾讯云 时间:2022-12-15 17:17:00


(资料图片仅供参考)

​PreparedStatement完成CURD和批处理

一、完成CURD

package com.lanson.test3;import com.lanson.entity.Emp;import java.sql.*;import java.util.ArrayList;import java.util.List;/** * @Author: Lansonli * @Description: MircoMessage:Mark_7001 */public class TestPreparedSstatement {    private static String driver ="com.mysql.cj.jdbc.Driver";    private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";    private static String user="root";    private static String password="root";    public static void main(String[] args) {        //testAdd();        //testUpdate();        //testDelete();        testQuery();    }    public static void testAdd(){        // 向 Emp表中增加一条数据        Connection connection = null;        PreparedStatement preparedStatement=null;        try{            Class.forName(driver);            connection = DriverManager.getConnection(url, user,password);            String sql="insert into emp values(DEFAULT ,?,?,?,?,?,?,?)";            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句            //设置参数            preparedStatement.setString(1,"Mark");            preparedStatement.setString(2,"MANAGER" );            preparedStatement.setInt(3,7839);            preparedStatement.setDate(4,new Date(System.currentTimeMillis()));            preparedStatement.setDouble(5,3000.12);            preparedStatement.setDouble(6,0.0);            preparedStatement.setDouble(7,30);            //执行CURD            int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句            System.out.println(rows);        }catch (Exception e){            e.printStackTrace();        }finally {            if(null != preparedStatement){                try {                    preparedStatement.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != connection){                try {                    connection.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }    }    public static void testUpdate(){        // 根据工号修改员工表中的数据        Connection connection = null;        PreparedStatement preparedStatement=null;        try{            Class.forName(driver);            connection = DriverManager.getConnection(url, user,password);            String sql="update emp set ename =? ,job=? where empno =?";            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句            //设置参数            preparedStatement.setString(1,"Jhon");            preparedStatement.setString(2,"ANALYST" );            preparedStatement.setInt(3,7935);            //执行CURD            int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句            System.out.println(rows);        }catch (Exception e){            e.printStackTrace();        }finally {            if(null != preparedStatement){                try {                    preparedStatement.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != connection){                try {                    connection.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }    }    public static void testDelete(){        // 根据工号删除员工表中的数据        Connection connection = null;        PreparedStatement preparedStatement=null;        try{            Class.forName(driver);            connection = DriverManager.getConnection(url, user,password);            String sql="delete from emp where empno =?";            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句            //设置参数            preparedStatement.setInt(1,7935);            //执行CURD            int rows =preparedStatement.executeUpdate();// 这里不需要再传入SQL语句            System.out.println(rows);        }catch (Exception e){            e.printStackTrace();        }finally {            if(null != preparedStatement){                try {                    preparedStatement.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != connection){                try {                    connection.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }    }    public static void testQuery(){        // 查询名字中包含字母A的员工信息        Connection connection = null;        PreparedStatement preparedStatement=null;        ResultSet resultSet=null;        List list =null;        try{            Class.forName(driver);            connection = DriverManager.getConnection(url, user,password);            /*             * 1使用PreparedStatement语句对象防止注入攻击             * 2PreparedStatement 可以使用 ? 作为参数的占位符             * 3使用?作为占位符,即使是字符串和日期类型,也不使用单独再添加 ""             * 4connection.createStatement();获得的是普通语句对象 Statement             * 5connection.prepareStatement(sql);可以获得一个预编译语句对象PreparedStatement             * 6如果SQL语句中有?作为参数占位符号,那么要在执行CURD之前先设置参数             * 7通过set***(问号的编号,数据) 方法设置参数             * */            String sql="select * from emp where ename like ? ";            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句            //设置参数            preparedStatement.setString(1,"%A%");            //执行CURD            resultSet = preparedStatement.executeQuery();// 这里不需要再传入SQL语句            list=new ArrayList() ;            while(resultSet.next()){                int empno = resultSet.getInt("empno");                String ename = resultSet.getString("ename");                String job = resultSet.getString("job");                int mgr = resultSet.getInt("mgr");                Date hiredate = resultSet.getDate("hiredate");                double sal= resultSet.getDouble("sal");                double comm= resultSet.getDouble("comm");                int deptno= resultSet.getInt("deptno");                Emp emp =new Emp(empno, ename, job, mgr, hiredate, sal, comm, deptno);                list.add(emp);            }        }catch (Exception e){            e.printStackTrace();        }finally {            if(null != resultSet){                try {                    resultSet.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != preparedStatement){                try {                    preparedStatement.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != connection){                try {                    connection.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }        // 遍历集合        for (Emp emp : list) {            System.out.println(emp);        }    }}

二、批处理

1、什么是批处理

当我们有多条sql语句需要发送到数据库执行的时候,有两种发送方式,一种是执行一条发送一条sql语句给数据库,另一个种是发送一个sql集合给数据库,也就是发送一个批sql到数据库。普通的执行过程是:每处理一条数据,就访问一次数据库;而批处理是:累积到一定数量,再一次性提交到数据库,减少了与数据库的交互次数,所以效率会大大提高,很显然两者的数据库执行效率是不同的,我们发送批处理sql的时候数据库执行效率要高。

2、statement语句对象实现批处理有如下问题

缺点:采用硬编码效率低,安全性较差。

原理:硬编码,每次执行时相似SQL都会进行编译

3、 PreparedStatement+批处理

优点:语句只编译一次,减少编译次数。提高了安全性(阻止了SQL注入)

原理:相似SQL只编译一次,减少编译次数

注意: 需要设置批处理开启&rewriteBatchedStatements=true

package com.lanson.test4;import java.sql.*;/** * @Author: Lansonli * @Description: MircoMessage:Mark_7001 */public class TestBatch {    private static String driver ="com.mysql.cj.jdbc.Driver";    private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";    private static String user="root";    private static String password="root";    public static void main(String[] args) {        testAddBatch();    }    // 定义一个方法,向部门表增加1000条数据    public static void testAddBatch(){        Connection connection = null;        PreparedStatement preparedStatement=null;        try{            Class.forName(driver);            connection = DriverManager.getConnection(url, user,password);            String sql="insert into dept values (DEFAULT ,?,?)";            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句            //设置参数            for (int i = 1; i <= 10663; i++) {                preparedStatement.setString(1, "name");                preparedStatement.setString(2, "loc");                preparedStatement.addBatch();// 将修改放入一个批次中                if(i%1000==0){                    preparedStatement.executeBatch();                    preparedStatement.clearBatch();// 清除批处理中的数据                }            }            /*            * 整数数组中的元素代表执行的结果代号            * SUCCESS_NO_INFO -2            * EXECUTE_FAILED  -3            * */            /*int[] ints = */            preparedStatement.executeBatch();            preparedStatement.clearBatch();        }catch (Exception e){            e.printStackTrace();        }finally {            if(null != preparedStatement){                try {                    preparedStatement.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }            if(null != connection){                try {                    connection.close();                } catch (SQLException e) {                    e.printStackTrace();                }            }        }    }}

上一篇:

下一篇:

X 关闭

热门推荐

北京解除大风蓝色预警信号_环球新视野

2022-12-15   北京日报客户端

第12届海外英才北京行即将启幕

2022-12-15   北京青年报官网

花都奇兵小说(花都奇兵)

2022-12-15   万能网

f 35战机图片(f 22p)

2022-12-15   万能网

摇酒壶使用技巧(摇酒壶)

2022-12-15   万能网

国家文创实验区50家园区全面复工

2022-12-15   北京青年报官网

北京市公园游览年票今起发售:全球时讯

2022-12-15   北京青年报官网

顺义突发事件应急预案体系建设完成

2022-12-15   北京青年报官网

精准呵护1亿个体户

2022-12-15   海外网

各省第一波感染高峰时间预测-焦点快看

2022-12-14   金融学家宏皓教授

一体锅(一体一魄)

2022-12-14   万能网

全球速读:巴伊色哥事件

2022-12-14   万能网

直播推荐|物理老师带您书画入门

2022-12-14   蝌蚪五线谱

明起三天京城多大风天气,气温持续走低

2022-12-14   北京日报客户端

《解码中国美好生活:甘肃实践》宣传片

2022-12-14   中国网`中国发展门户网

浙人社发No.2011221:每日头条

2022-12-14   万能网

天天速读:江汽集团11月销量环比增长11.87%

2022-12-14   中国产业经济信息网

世界杯球迷热捧“中国制造”:天天热消息

2022-12-14   中国产业经济信息网

短讯!本市700名中小学生线上比拼机器人

2022-12-14   北京青年报官网

全新人少好遛娃,安全玩耍先收藏

2022-12-14   北京青年报官网

【环球热闻】顺义开展安全生产专题培训

2022-12-14   北京青年报官网

华北鞋城(华北鞋城)

2022-12-13   万能网

冰恋是什么意思?

2022-12-13   万能网

排除万难干起来跑起来|报道

2022-12-13   长安观察

Copyright   2015-2022 中国行业信息网版权所有  备案号:   联系邮箱:29 59 11 57 8@qq.com