没有ORM框架时如何操作数据库及其中的缺点

1. 没有ORM框架时的情况

让我们回顾下,之前没有ORM框架时,是如何使用JDBC操作数据库的。

1.1 查询,使用Statement,有被SQL注入攻击的危险

        try {

         Class.forName("com.mysql.jdbc.Driver").newInstance();

         Connection con = DriverManager.getConnection(dbURL, userName, userPwd);

         String name="Bee'  or '1'='1' -- ";  //会被SQL注入攻击

         String word="aaa";

         String sql="select * from users where name='"+name+"' and word='"+word+"'";

        

         Statement stmt = con.createStatement();

         ResultSet rs =stmt.executeQuery(sql);

         while(rs.next()){

              //在此处获取结果. 手动封装成Javabean

             System.out.println(rs.getString(2));

             }

         System.out.println("");

         }catch(SQLException e){

             System.out.println("have exception"+e.getMessage());

         }

 

 

1.2  查询,使用PreparedStatement, 可以防止SQL注入攻击

        try {

         Class.forName("com.mysql.jdbc.Driver").newInstance();

         Connection con = DriverManager.getConnection(dbURL, userName, userPwd);

         String sql="select * from users where name=? and word=?";

         PreparedStatement stmt = con.prepareStatement(sql);

         stmt.setString(1, "Bee'  or '1'='1'");//防止SQL注入攻击

         stmt.setString(2,"aaa");

         ResultSet rs = stmt.executeQuery();

         while(rs.next()){

              //在此处获取结果. 手动封装成Javabean

             System.out.println(rs.getString(2));

             }

         System.out.println("");

         }catch(SQLException e){

             System.out.println("have exception"+e.getMessage());

         }

  总结直接使用JDBC,存在的工作量或问题,主要有:

  1. 需要开发人员自己维护Connection数据库连接。
  2. 事务需要自己实现。
  3. 需要手动写sql语句,工作量大,烦琐;难于调试,经常会出现sql多一个单引号等引发的sql语法问题;且不同的sql语句需要重新调试。
  4. 手动编写代码设置参数,如:stmt.setString(2,"aaa");。
  5. 手动将查询结果拼装成Javabean对象返回。spring的JdbcTemplate也存在这个问题。

针对每个实体写一份dao操作文件,n个实体就要写n份。

你可能感兴趣的:(Bee,ORM,Java)