MySQL出现 Operation not allowed after ResultSet closed错误

今天测试增删查改的删除操作时,出现以下Operation not allowed after ResultSet closed的错误

原代码如下:

public static boolean insertUser(UserDTO _user) throws SQLException{
		boolean bool =false;
		Connection conn =null;
		Statement stmt = null;
        ResultSet res = null;
		conn = DataAccesss.getConnection();
		stmt = conn.createStatement();
		
		
		res = stmt.executeQuery("select * from userr where uname ='"+_user.getUname()+"'");//先查询数据库中是否存在该用户名,无论是软删除或仍存在不能插入。
		if(res.next()==false) {
			int num = stmt.executeUpdate("insert into userr values ('"+_user.getUname()+"','"+_user.getUpassword()+"','"+_user.getTel()+"','"+_user.getSurperuser()+"','"+_user.getFlag()+"')");
			System.out.println("已成功执行"+num+"行插入成功");
			
		}
		else {System.out.println("用户名已存在");}
		if(res.getInt("flag")==1) 
			System.out.println("该用户被软删除,存在数据库中");
		
		DataAccesss.closeConnection(conn, stmt,res);
		return bool=true;
	}
	

这是由于多个一个stmt多个rs进行操作引起的ResultSet已经关闭的错误

一个stmt多个rs进行操作.
那么从stmt得到的rs1,必须马上操作此rs1后,才能去得到另外的rs2,再对rs2操作.
不能互相交替使用,会引起rs已经关闭错误.

/* 插入功能
	 * 参数列表传入userr实例
	 * 往表格最后输入一行元祖
	 * 打印插入行数插入是否成功
	 * (需要修改权限,用户自己可以设置自己权限??!!)
	 */
	public static boolean insertUser(UserDTO _user) throws SQLException{
		boolean bool =false;
		Connection conn =null;
		Statement stmt = null;
        ResultSet res = null;
		conn = DataAccesss.getConnection();
		stmt = conn.createStatement();
		
		
		res = stmt.executeQuery("select * from userr where uname ='"+_user.getUname()+"'");//先查询数据库中是否存在该用户名,无论是软删除或仍存在不能插入。
		if(res.next()==false) {
			int num = stmt.executeUpdate("insert into userr values ('"+_user.getUname()+"','"+_user.getUpassword()+"','"+_user.getTel()+"','"+_user.getSurperuser()+"','"+_user.getFlag()+"')");
			System.out.println("已成功执行"+num+"行插入成功");
			bool=true;
			
		}
		else {System.out.println("用户名已存在");
		if(res.getInt("flag")==1) 
			System.out.println("该用户被软删除,存在数据库中");}
		
		DataAccesss.closeConnection(conn, stmt,res);
		return bool;
	}

一个stmt最好对应一个rs, 如果用一个时间内用一个stmt打开两个rs同时操作,会出现这种情况.
所以解决此类问题:1.就多创建几个stmt,一个stmt对应一个rs;2.若用一个stmt对应多个rs的话,那只能得到一个rs后就操作,处理完第一个rs后再处理其他的

stmt=conn.createStatement();
stmt2=conn.createStatement();
rs=stmt.executeQuery("select * from t1");
rst=stmt2.executeQuery("select * from t2");
rs.last();
rst.last();
--------------------- 
 

扫描二维码关注公众号,回复: 5619320 查看本文章

猜你喜欢

转载自blog.csdn.net/heihei2017/article/details/83059766