今天来总结一下execute和executeUpdate的相同点和不同点。
相同点:
在jdbc中,execute和executeUpdate都可以执行增加,删除,修改。
具体例子:
package jdbc5;
import java.sql.*;
public class test1 {
public static void main(String[] args) {
Connection c = null;
Statement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
String sqlInsert = "insert into Hero values (null,'盖伦',616,100)";
String sqlDelete = "delete from Hero where id = 100";
ps = c.createStatement();
ps.execute(sqlInsert);
ps.execute(sqlDelete);
ps.executeUpdate(sqlInsert);
ps.executeUpdate(sqlDelete);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
if(ps != null) {
try {
ps.close();
}catch(Exception e) {
e.printStackTrace();
}
ps = null;
}
if(c != null) {
try {
c.close();
}catch(Exception e) {
e.printStackTrace();
}
c = null;
}
}
}
}
运行完上述程序,去mysql中查看发现二者的运行效果是完全相同的,也就是说execute与executeUpdate都可以执行增,删,改操作。
不同点:
不同1:
execute可以执行查询语句
然后通过getResultSet,把结果集取出来
executeUpdate不能执行查询语句
不同2:
execute返回boolean类型,true表示执行的是查询语句,false表示执行的是insert,delete,update等等
executeUpdate返回的是int,表示有多少条数据受到了影响
代码如下:
package jdbc5;
import java.sql.*;
public class test2 {
public static void main(String[] args) {
Connection c = null;
Statement s = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin");
s = c.createStatement();
String sql = "select * from hero";
s.execute(sql);
rs = s.getResultSet();
while(rs.next()) System.out.println(rs.getInt("id"));
boolean isselect = s.execute(sql);//execute查询语句所以输出true
System.out.println(isselect);
String sqlupdate = "update Hero set hp = 300 where id < 100";
int b = s.executeUpdate(sqlupdate);//executeUpdate输出受影响的数量
System.out.println(b);
}catch(ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(rs != null) {
try {
rs.close();
}catch(Exception e) {
e.printStackTrace();
}
rs = null;
}
if(s != null) {
try {
s.close();
}catch(Exception e) {
e.printStackTrace();
}
s = null;
}
if(c != null) {
try {
c.close();
}catch(Exception e) {
e.printStackTrace();
}
c = null;
}
}
}
}