zoukankan      html  css  js  c++  java
  • java第八次实验作业

    (一)学习总结

    (二)通过实验内容中的具体实例说明在执行executeUpdate()方法和executeQuery()方法中使用动态参数时,为什么要使用PreparedStatement接口而不使用Statement,比较使用两种接口的不同之处。

    // 获取所有数据
    public ArrayList<Pet> queryAllData() 
    { Connection conn=null;       
    Statement stmt=null; ResultSet rs=null; 
    ArrayList<Pet> list=new 
    ArrayList<Pet>();
    try{ conn=JDBCUtils.getConnection(1);
    
    //获得链接对象,用SQLSEVER数据库连接方法
    stmt=conn.createStatement();
    //建立SQL语句的对象,对象类型为Statement接口 
    String sql="select no,variety,age,sums,price from pet";
    //查询语句 rs=stmt.executeQuery(sql);
    //执行SQL查询语句 
    while(rs.next())
    { Pet thisPet=new Pet();             
    thisPet.setNo(rs.getString("no"));                                     
    thisPet.setVariety(rs.getString("variety"));                    
    thisPet.setAge(rs.getInt("age"));                                     
    thisPet.setSum(rs.getInt("sums"));                                     
    thisPet.setPrice(rs.getDouble("price"));                               
    list.add(thisPet);
    //将查询出的这个宠物信息存放到list宠物集合中 
    } return list; 
    }catch(Exception e)
    { e.printStackTrace(); }
    finally{ JDBCUtils.close(conn); } 
    return null; } 
    // 删除数据 
    public boolean delPet(String delNo)
    { boolean result=false; Connection conn=null;
    PreparedStatement pstmt=null; 
    try{ conn=JDBCUtils.getConnection(1);
    //用SQLSEVER数据库连接方法连接 
    String sql="delete from pet where no=?"; 
    pstmt=conn.prepareStatement(sql); 
    pstmt.setString(1, delNo); 
    if(pstmt.executeUpdate()>0){ result=true; } 
    }catch(Exception e){ e.printStackTrace(); 
    }finally{ JDBCUtils.close(conn); } 
    return result; }
    因为在没有动态参数使用Statement接口,在添加和删除操作时(执行的语句中含动态参数),用了PreparedStatement接口。
    执行静态SQL语句时,通常通过Statement实例实现;
    执行数据查询语句时,如SELECT语句,使用Statement对象的executeQuery 方法执行。
    PreparedStatement接口会用Connection对象的prepareStatement()方法创建一个preparedStatement对象来执行SQL语句,而Statement的接口会用Connection对象的createStatement()方法创建一个Statement对象来执行SQL语句,PreparedStatement接口用在SQL语句中有动态变量的情况,而Statement的接口用在SQL语句没有动态变量的情况。
    

    (三)实验总结
    https://git.oschina.net/hebau_cs15/Java-CS01QH.git

  • 相关阅读:
    第三次随笔作业
    第二次随笔作业
    第一次随笔
    第四次随笔作业
    第三次随笔作业
    第二次随笔作业
    第一次博客
    第四次作业
    第三次作业(2)
    第二次随笔(修改版3)
  • 原文地址:https://www.cnblogs.com/JoeH/p/6875895.html
Copyright © 2011-2022 走看看