zoukankan      html  css  js  c++  java
  • JDBC中PreparedStatement接口提供的execute、executeQuery和executeUpdate之间的区别及用法

    JDBC中PreparedStatement接口提供的execute、executeQuery和executeUpdate之间的区别及用法

     (2012-08-27 09:36:18)
    标签: 

    statement

     

    execute

     

    executequery

     

    executeupdate

     

    杂谈

    分类: DataBase区
       PreparedStatement接口提供了三种执行 SQL 语句的方法:executeQuery、executeUpdate 和 execute。使用哪一个方法由 SQL 语句所产生的内容决定。

          1、方法executeQuery
             用于产生单个结果集的语句,例如 SELECT 语句。 被使用最多的执行 SQL 语句的方法是 executeQuery。这个方法被用来执行 SELECT 语句,它几乎是使用最多的 SQL 语句。

           2、方法executeUpdate
             用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。INSERT、UPDATE 或 DELETE 语句的效果是修改表中零行或多行中的一列或多列。executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。

             使用executeUpdate方法是因为在 createTableCoffees 中的 SQL 语句是 DDL (数据定义语言)语句。创建表,改变表,删除表都是 DDL 语句的例子,要用 executeUpdate 方法来执行。你也可以从它的名字里看出,方法 executeUpdate 也被用于执行更新表 SQL 语句。实际上,相对于创建表来说,executeUpdate 用于更新表的时间更多,因为表只需要创建一次,但经常被更新。


            3、 方法execute:
             用于执行返回多个结果集、多个更新计数或二者组合的语句。也可用于执行 INSERT、UPDATE 或 DELETE 语句。

    用法举例:

    1、增加、修改、删除都用execute(),也可用executeUpdate(),针对于INSERT、UPDATE 或 DELETE 语句

        public int addAirEnvironmentPresent(M_AirEnviromentPresentDTO airDTO){
      int index = 1;
      String sql = "insert into airPresent(airForecastPlace,ForecastTime,TSPvalue,remark) values(?,?,?,?)";
      try {
       ps = conn.prepareStatement(sql);
       ps.setString(index++, airDTO.getAirForecastPlace());
       ps.setString(index++, airDTO.getForecastTime());
       ps.setString(index++, airDTO.getTSPvalue());
       ps.setString(index++, airDTO.getRemark());
       ps.execute();
       
      } catch (SQLException e) {
       e.printStackTrace();
      }
      return 1;
     }

    2、查询调用executeQuery(),针对于SELECT语句

    public ArrayList getAirEnvironmentPresentAll(){
      ArrayList list = new ArrayList();
      String sql = "select * from airPresent";
      try {
       ps = conn.prepareStatement(sql);
       rs = ps.executeQuery();
       while(rs.next()){
        dto = new M_AirEnviromentPresentDTO();
        dto.setId(rs.getInt("id"));
        dto.setAirForecastPlace(rs.getString("airForecastPlace"));
        dto.setForecastTime(rs.getString("forecastTime"));
        dto.setTSPvalue(rs.getString("tspvalue"));
        dto.setRemark(rs.getString("remark"));
        list.add(dto);
       }
      } catch (SQLException e) {
       e.printStackTrace();
      }
      return list;
     }

  • 相关阅读:
    CSS印象不深的小地方
    gulp常用插件的使用
    移动端手势库Hammer.js—增强touch事件或手势
    HTML5拖放与文件操作api,实现拖拽上传文件功能
    Less相关
    gulp使用(一)
    将博客搬至CSDN
    jquery Ajax 通过jsonp的方式跨域提交表单
    解决“The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path”问题
    使用eclipse4.5创建maven项目
  • 原文地址:https://www.cnblogs.com/hewei-666/p/7497266.html
Copyright © 2011-2022 走看看