JDBC中Statement接口提供的execute、executeQuery和executeUpdate之間的區別
Statement 接口提供了三種執行 SQL 語句的方法:executeQuery、executeUpdate 和 execute。使用哪一個方法由 SQL 語句所產生的內容決定。
方法executeQuery
ResultSet executeQuery(String sql)
執行給定的 SQL 語句,該語句返回單個 ResultSet 對象。這個方法被用來執行 SELECT 語句,它幾乎是使用最多的 SQL 語句。
ResultSet一定要.next一下,不然開始的位置是空的
-
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
-
sql = "select * from base_of_ad.ad_list";
-
ResultSet rs = stmt.executeQuery(sql);
-
System.out.println(rs.getRow()); //rs.getRow()獲得結果集的當前行號(1、2、3等),初始爲0
-
while(rs.next()){
-
name = rs.getString(3); //取得所在行第三列的String值
-
System.out.println("name="+name);
-
}
方法executeUpdate
int executeUpdate(String sql)
用於執行 INSERT、UPDATE 或 DELETE 語句以及 SQL DDL(數據定義語言)語句,例如 CREATE TABLE 和 DROP TABLE。INSERT、UPDATE 或 DELETE 語句的效果是修改表中零行或多行中的一列或多列。executeUpdate 的返回值是一個整數,指示受影響的行數(即更新計數)。對於 CREATE TABLE 或 DROP TABLE 等不操作行的語句,executeUpdate 的返回值總爲零。返回值爲-1代表更新不成功。
-
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
-
sql = "update ad_list set name = '小紅' where id=1";
-
//sql = "select * from mysql.user";
-
int result = stmt.executeUpdate(sql);
-
if(result != -1){
-
System.out.println("更新 ok");
-
}
用於執行返回多個結果集、多個更新計數或二者組合的語句。因爲多數程序員不會需要該高級功能