execute与executeUpdate的区别

今天来总结一下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;
			}
		}
	}
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值