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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM