Java中PreparedStatement和Statement

五迷三道 提交于 2019-12-27 01:44:54

preparedStatement 有三大优点:

一,代码的可读性和可维护性

二,PreparedStatement尽最大可能提高性能,有预编译功能

三,最重要的一点是极大地提高了安全性.

第一点直接看两者代码对比

   public static void main(String[] args) {
  
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
  
        String sql = "insert into hero values(null,?,?,?)";
        try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
            Statement s = c.createStatement();
            PreparedStatement ps = c.prepareStatement(sql);
        ) {
           //  Statement需要进行字符串拼接,可读性和维修性比较差
            String sql0 = "insert into hero values(null," + "'提莫'" + "," + 313.0f + "," + 50 + ")";
            s.execute(sql0);
  
            // PreparedStatement 使用参数设置,可读性好,不易犯错
            // "insert into hero values(null,?,?,?)";
            ps.setString(1, "大大大多提");
            ps.setFloat(2, 313.0f);
            ps.setInt(3, 50);
            ps.execute();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  
    }

 第二点主要原因是因为存在预编译能力

https://blog.csdn.net/zhangw1236/article/details/59113941

https://blog.csdn.net/coco0930/article/details/92711179

第三点是防止sql注入

https://blog.csdn.net/czh500/article/details/88202971

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!