2021-08-02 JDBC优化和事务和Properies

JDBC优化

  1. 代码优化
public class Test {
    public static void main(String[] args){
        Connection conn = null;
        Statement state = null;
        ResultSet rs = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
            String sql = "Select * from teacher";
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            while(rs.next()){
                System.out.println(rs.getString("Tid"));
                System.out.println(rs.getString("Tname"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
                try {
                    if(rs != null){
                    rs.close();
                    }
                    if(state != null){
                        state.close();
                    }
                    if(conn != null){
                        conn.close();
                    }
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }
}
  1. DML
    Data Manipulation Language : 数据操作语言
    涉及的关键字有 : delete,update,insert
    和查询的操作几乎一样,就是把第4步和第5步更改一下
    插入
  public class Test02 {
        public static void main(String[] args){
            Connection conn = null;
            Statement state = null;
            ResultSet rs = null;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
                String sql = "INSERT INTO teacher (Tid,Tname)VALUES('03','陶老师');";
                state = conn.createStatement();
                int count = state.executeUpdate(sql);
                System.out.println("插入了"+count+"条数据");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try{
                    if(rs != null){
                        rs.close();
                    }
                    if(state != null){
                        state.close();
                    }
                    if(conn != null){
                        conn.close();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
  1. PreparedStatement
    添加或者更新的时候,尽量使用 PreparedStatement ,而不是使用Statement
    Statement 和 PreparedStatement 的区别
    Statement用于执行静态SQL语句,在执行的时候,必须指定一个事先准备好的SQL语句,并且相对不安全,会有SQL注入的风险
    PreparedStatement是预编译的SQL语句对象,sql语句被预编译并保存在对象中, 被封装的sql语句中可以使用动态包含的参数 ? ,
    在执行的时候,可以为?传递参数
    使用PreparedStatement对象执行sql的时候,sql被数据库进行预编译和预解析,然后被放到缓冲区,
    每当执行同一个PreparedStatement对象时,他就会被解析一次,但不会被再次编译 可以重复使用,可以减少编译次数,提高数据库性能
    并且能够避免SQL注入,相对安全(把’ 单引号 使用 \ 转义,避免SQL注入 )
    使用PreparedStatement 执行查询
 public class Test03 {
        public static void main(String[] args){
            m1("01");
        }
        public static void m1(String Tid){
            Connection conn = null;
            PreparedStatement prst = null;
            ResultSet rs = null;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
                String sql ="select * from teacher where Tid = ?";
                prst = conn.prepareStatement(sql);
                // 设置第一个?的值
                prst.setString(1, Tid);
                rs = prst.executeQuery();
                while(rs.next()){
                    System.out.println(rs.getString("Tid") + "   ");
                    System.out.println(rs.getString("Tname") + "   ");
                    
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                try {
                    // 关闭资源,从上到下依次关闭,后打开的先关闭
                    if (rs != null) {
                        rs.close();
                    }
                    if (prst != null) {
                        prst.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }

        }
    }
使用PreparedStatement 执行增删改,以添加为例
 

    public class Test04 {
        public static void main(String[] args){
            m1("05","韩金龙");
        }
        public static void m1(String Tid,String Tname){
            Connection conn = null;
            PreparedStatement prst = null;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
                String sql = "insert into teacher (Tid,Tname)values(?,?)";
                prst = conn.prepareStatement(sql);
                prst.setString(1,Tid);
                prst.setString(2,Tname);
                int count = prst.executeUpdate();
                System.out.println("插入了"+count+"条数据");
                
            }catch(Exception e){
                e.printStackTrace();
            }finally {
                try {
                    // 关闭资源,从上到下依次关闭,后打开的先关闭
                    if (prst != null) {
                        prst.close();
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }

        }
    }
  1. 封装工具类
    主要针对创建链接和关闭连接进行封装。
public class JDBCUtil {
    public static Connection getConnection() throws ClassNotFoundException, SQLException{
        String username = "root";
        String password = "root";
        String url = "jdbc:mysql://127.0.0.1:3306/test";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(url, username, password);
        return connection;
    }
    public static void close(AutoCloseable obj){
        if(obj != null){
            try {
                obj.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
}
  1. Batch多语句操作
    5.1 Statement 实现
  public class Test05 {
        public static void main(String[] args){
            Connection conn = null;
            Statement state = null;
            try{
                conn = JDBCUtil.getConnection();
                state = conn.createStatement();
                state.addBatch("insert into teacher (Tid,Tname)values('06','孙悟空')");
                state.addBatch("insert into teacher (Tid,Tname)values('07','韩欣欣')");
                state.addBatch("insert into teacher (Tid,Tname)values('08','陶佳怡')");
                state.executeBatch();
                System.out.println("添加成功");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                JDBCUtil.close(state);
                JDBCUtil.close(conn);
            }
        }
    }
5.2 PreparedStatement 实现
   public class Test06 {
        public static void main(String[] args){
            Connection conn = null;
            PreparedStatement prst = null;
            try{
                conn = JDBCUtil.getConnection();
                String sql = "insert into teacher (Tid,Tname)values(?,?)";
                prst = conn.prepareStatement(sql);
                prst.setString(1,"09");
                prst.setString(2,"李大为");
                prst.addBatch();
                prst.setString(1,"10");
                prst.setString(2,"韩建国");
                prst.addBatch();
                prst.executeBatch();
                System.out.println("添加成功");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                JDBCUtil.close(prst);
                JDBCUtil.close(conn);
            }
        }
    }

事务

1.事务机制管理
Transaction事务机制管理
默认情况下,是执行一条SQL语句就保存一次,那么比如我需要 有三条数据同时成功同时失败,这个时候就需要开启事务机制了
如果开启事务机制,执行中发生问题,会回滚到没有操作之前,相当于什么也没有发生过
1) 没有事务处理的操作

  public class Test07 {
        public static void main(String[] args){
            Connection conn = null;
            PreparedStatement prst = null;
            try{
                conn = JDBCUtil.getConnection();
                String sql = "insert into teacher (Tid,Tname)values(?,?)";
                prst = conn.prepareStatement(sql);
                prst.setString(1,"11");
                prst.setString(2,"张天");
                prst.addBatch();
                prst.setString(1,"11");
                prst.setString(2,"张你鸟");
                prst.addBatch();
                prst.setString(1,"12");
                prst.setString(2,"无梦山");
                prst.addBatch();
                prst.executeBatch();
                System.out.println("添加成功");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                JDBCUtil.close(prst);
                JDBCUtil.close(conn);
            }
        }
    }
2) 有事务机制处理的操作
   
    public class Test08 {
        public static void main(String[] args){
            Connection conn = null;
            Statement state = null;
            ResultSet rs = null;
            try{
                conn = JDBCUtil.getConnection();
                // 关闭自动提交
                conn.setAutoCommit(false);
                state = conn.createStatement();
                state.addBatch("insert into teacher (Tid,Tname)values('13',小子)");
                state.addBatch("insert into teacher (Tid,Tname)values('12','王美丽')");
                // 执行缓存中所有SQL
                state.executeBatch();
                System.out.println("添加成功");
                conn.commit();
                conn.setAutoCommit(true);
            }catch(Exception e){
                e.printStackTrace();
                try {
                    //事务回滚
                    conn.rollback();
                    conn.setAutoCommit(true);
                } catch (SQLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }finally{
                JDBCUtil.close(rs);
                JDBCUtil.close(state);
                JDBCUtil.close(conn);
            }
        }
    }

Properies

  1. Properties 优化硬代码
    如上,我们项目开发完成测试通过后,通常是要打包发布给别人使用的,如果我们把一些配置信息写死到代码中(这种行为叫硬编码,hardcode),
    别人就无法修改了
    比如别人使用的MySQL服务器对应的IP是10.0.0.1,端口号是9300,用户名是mysqluser、密码是123456。
    那么我们只能改代码再重新打包发布,如果有多个用户,他们对应的配置信息都不同,那么我们要针对不同的用户打包发布多次。
    以上显然是没必要的,因为我们开发的是程序,只要业务需求/逻辑不变,我们就无需多次打包发布。对此我们的解决方案是,尽量避免硬编码,
    将数据与程序分离解耦,将配置信息存储到配置文件中,程序运行时读取配置文件,不同用户只需按自己的实际情况修改配置文件即可。
    1) 创建jdbc.properties配置文件
    这种方式 账号密码什么的如果发生改动,我只需要更改配置文件就可以
    在src目录下创建jdbc.properties文件,内容如下
    driver = com.mysql.jdbc.Driver;
    url = jdbc:mysql://127.0.0.1:3306/test;
    username = root;
    password = root;
    2) 更改DBUtil工具类
 

   public class JDBCUtil {
        public static Connection getConnection() throws ClassNotFoundException, SQLException, IOException{
            Properties properties = PropertiesUtil.getProperties();
                    // getClassLoader : 获取类加载器
                    // getResourceAsStream : 把资源转换为流
                    // 这里 定位到src.所以可以直接写文件名,而流是定位到项
                    // properties 本质就是一个map,可以通过key获取value
                    // username=root 读取到之后,以 = 分隔为数组,把username作为key,root作为value保存
                    // 所以我们就可以通过username 来获取root
                    String driver = properties.getProperty("driver");
                    String url = properties.getProperty("url");
                    String username = properties.getProperty("username");
                    String password = properties.getProperty("possword");
                    Class.forName(driver);
                    Connection connection = DriverManager.getConnection(url, username, password);
            return connection;
        }
        public static void close(AutoCloseable obj){
            if(obj != null){
                try {
                    obj.close();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }
3) 创建PropertiesUtil
public class PropertiesUtil {
        private static Properties jdbcProperties = null;
        private PropertiesUtil(){}
        public static Properties getProperties(){
                    try {
                        if(jdbcProperties != null){
                            jdbcProperties = new Properties();
                        jdbcProperties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
                        }
                    }catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
            return jdbcProperties;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值