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;
     }

  • 相关阅读:
    Spring@Profile注解
    day 32 子进程的开启 及其用法
    day 31 udp 协议SOCK_DGRAM
    day 30 客户端获取cmd 命令的步骤
    day 29 socket 理论
    day 29 socket 初级版
    有关 组合 继承
    day 27 多态 接口 类方法 静态方法 hashlib 摘要算法模块
    新式类和经典类的区别
    day 28 hasattr getattr serattr delattr 和带__内置__ 类的内置方法
  • 原文地址:https://www.cnblogs.com/hewei-666/p/7497266.html
Copyright © 2011-2022 走看看