execute、executeUpdate、executeQuery三者的区别

2020-7-21 杨静

execute、executeUpdate、executeQuery三者的区别','

1. ResultSet executeQuery(String sql); 执行SQL查询,并返回 ResultSet 对象。

例如:被执行最多的 SELECT 语句。

2.int executeUpdate(String sql); 可执行增,删,改,返回执行受到影响的行数。

例如: INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句

3. boolean execute(String sql); 可执行任何SQL语句,返回一个布尔值,表示是否返回 ResultSet 。

       execute是executeQuery和executeUpdate的综合.

通常我们没有必要使用execute方法来执行SQL语句,而是使用 executeQuery 或 executeUpdate 更适合。

-----

 

executeUpdate() 这是 PreparedStatement 接口中的方法

executeUpdate(String sql) 这是 PreparedStatement 从父接口 Statement 中继承过来的方法

executeUpdate() 中执行 SQL 语句需要在创建 PerparedStatement 时通过 Connection 的 prepareStatement(String sql) 方法中写出,因为 PerparedStatement 中的 SQL 语句数据库需要进行预编译和缓存,因此要在创建 PerparedStatement 对象时给出 SQL 语句。

而 executeUpdate(String sql) 是 Statement 中的方法,参数中的 SQL 语句只是提交给数据库去执行,并不需要预编译。

如果 SQL 语句中有 ? 占位符,那么在设置好占位符中的值后,必须使用 executeUpdate() 执行。而 executeUpdate(String sql) 只是提交一个 SQL 语句,且这个语句中不能带有 ? 占位符。

当然,我们最好不要用 Statement 接口
参考:http://www.cnblogs.com/bukudekong/archive/2011/06/22/2086531.html

发表评论:

@2024 HowTD 浙ICP备18004985号-2

浙公网安备 33010202001281号