转载:JDBC中PreparedStatement接口提供的execute、executeQuery和executeUpdate之间的区别及用法-java jdbc

JDBCPreparedStatement接口提供的executeexecuteQueryexecuteUpdate之间的区别及用法

      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 语句

  

 1  public int addAirEnvironmentPresent(M_AirEnviromentPresentDTO airDTO){
 2   int index = 1;
 3   String sql = "insert into airPresent(airForecastPlace,ForecastTime,TSPvalue,remark) values(?,?,?,?)";
 4   try {
 5    ps = conn.prepareStatement(sql);
 6    ps.setString(index++, airDTO.getAirForecastPlace());
 7    ps.setString(index++, airDTO.getForecastTime());
 8    ps.setString(index++, airDTO.getTSPvalue());
 9    ps.setString(index++, airDTO.getRemark());
10    ps.execute();
11   
12   } catch (SQLException e) {
13    e.printStackTrace();
14   }
15   return 1;
16  }

 

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

 1 public ArrayList getAirEnvironmentPresentAll(){
 2   ArrayList list = new ArrayList();
 3   String sql = "select * from airPresent";
 4   try {
 5    ps = conn.prepareStatement(sql);
 6    rs = ps.executeQuery();
 7    while(rs.next()){
 8     dto = new M_AirEnviromentPresentDTO();
 9     dto.setId(rs.getInt("id"));
10     dto.setAirForecastPlace(rs.getString("airForecastPlace"));
11     dto.setForecastTime(rs.getString("forecastTime"));
12     dto.setTSPvalue(rs.getString("tspvalue"));
13     dto.setRemark(rs.getString("remark"));
14     list.add(dto);
15    }
16   } catch (SQLException e) {
17    e.printStackTrace();
18   }
19   return list;
20  }

 

posted @ 2021-11-21 15:45  r涤生  阅读(369)  评论(0编辑  收藏  举报