您的位置:首页 > 产品设计 > UI/UE

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

2014-05-13 20:14 573 查看
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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐