java.sql.SQLException: 关闭的连接

最近做一个统计数据的小工具,发现在自己机器上运行正常,移到其他机器上就报:

java.sql.SQLException: 关闭的连接

的错误,开始以为是防火墙的问题,经过测试,发现和防火墙无关。

原来还是程序写得有问题,在获得数据库连接时,若重复使用Connection变量,则除了判断为空外,还要判断是否关闭,见下面代码黑体字部分。

	/**
	 * 获得数据库连接
	 * @return
	 */
	public Connection getConnection(){
		try {
			//判断有问题			
			//if(conn != null)
			//应该判断连接是否已关闭
			if(conn != null && !conn.isClosed())
     				return conn;

			String dbDriver = DBDRIVER;
			String dbUrl = DBURL;
			String dbUser = DBUSER;
			String dbPwd = DBPWD;
			
			Class.forName(dbDriver).newInstance();
			conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
			
			if(conn == null)
				throw new Exception("获取数据库连接失败!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}


 
否则有可能Connection 变量不为空(null),但出现连接已关闭的问题。

查询数据表处理见下面的函数: 

public void statOne(CaclCell cc) {
		try {		
			getConnection();			
			Statement st = conn.createStatement();
			String statYear = cc.getStatYear();
			String lastStatYear = cc.getLastStatYear();			
			String startDate = cc.getStartDate();
			String endDate = cc.getEndDate();
			
			String sql = cc.getSql();
			
			if(sql != null && !"".equals(sql.trim())){				
				String sql2 = sql.replace("[startDate]", startDate);
				sql2 = sql2.replace("[endDate]", endDate);
				sql2 = sql2.replace("[statYear]", statYear);
				sql2 = sql2.replace("[lastStatYear]", lastStatYear);				
				
				log.info("sql=" + sql2);
				
				ResultSet rs=st.executeQuery(sql2);
		
				rs.next();
				String result = rs.getString(1);
				cc.setResult(result);
				hmOutput.put(cc.getDataCell(), cc);
			}			conn.close();
			
		} catch (Exception e) {
			log.error("statOne failed.", e);
			try {
				if(conn != null)
					conn.close();
			} catch (Exception e2) {
				log.error("close database connection failed.", e2);
			}
		}finally{
			try {
				if(conn != null)
					conn.close();
			} catch (Exception e2) {
				log.error("close database connection failed.", e2);
			}
		}
	}


 

但若将代码做一些调整,错误又不出现了。

	/**
	 * 单子段统计
	 * 
	 */
	public void statOne(CaclCell cc) {
		try {	
	
			String statYear = cc.getStatYear();
			String lastStatYear = cc.getLastStatYear();			
			String startDate = cc.getStartDate();
			String endDate = cc.getEndDate();
			
			String sql = cc.getSql();
			
			if(sql != null && !"".equals(sql.trim())){				
				String sql2 = sql.replace("[startDate]", startDate);
				sql2 = sql2.replace("[endDate]", endDate);
				sql2 = sql2.replace("[statYear]", statYear);
				sql2 = sql2.replace("[lastStatYear]", lastStatYear);				
				
				log.info("sql=" + sql2);
				getConnection();				
				Statement st = conn.createStatement();
				ResultSet rs=st.executeQuery(sql2);
		
				rs.next();
				String result = rs.getString(1);
				cc.setResult(result);
				hmOutput.put(cc.getDataCell(), cc);
				
				conn.close();			
			}
						
		} catch (Exception e) {
			log.error("statOne failed.", e);
			try {
				if(conn != null)
					conn.close();
			} catch (Exception e2) {
				log.error("close database connection failed.", e2);
			}
		}
	}


 也就是getConnection()紧挨executeQuery() 语句。

 原因是什么呢,其实和黑体代码位置没有关系。而是如果放在if语句中,则只需要一个连接(只有一条满足要处理条件),而如果statOne()调用两次,则出现了同样的问题。

说明什么呢:conn.close(); 数据库连接关闭后,conn并不会为空。

所以要使用conn.isClosed()来判断数据库连接是否已关闭,如关闭则重新建立连接,如没关闭则继续使用;

黑体字没有正常显示,见<strong></strong>包含部分 

 

补充说明:

连接建立需要较长时间,我的双CPU性能很好的机器要5秒左右,如果每次处理都关闭后再连接,系统运行势必会非常的慢。可以在处理完所有的数据后再关闭数据库连接,这样就能获得较高的处理性能。

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package druidJDBCUtils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class DruidJDBCUtils { //定义成员变量 private static DataSource ds; //静态代码块加载配置文件 static { try { Properties prop = new Properties(); InputStream is = DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); prop.load(is); ds = DruidDataSourceFactory.createDataSource(prop); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取数据库连接对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 获取连接池方法 */ public static DataSource getDataSource(){ return ds; } /** * 关闭资源方法 * close()查询sql方法 */ public static void close(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 关闭资源方法 * close()增删改sql方法 */ public static void close(Statement statement, Connection connection) {
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
package cn; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; //登陆面板 public class Login extends JFrame { Connection conn = null; Statement stmt = null; ResultSet rst = null; public Login() { try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("加载驱动成功。"); String url = "jdbc:mysql://localhost/users"; String user = "root"; String password = "123456"; conn = DriverManager.getConnection(url, user, password); System.out.println("连接数据库成功。"); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); rst = stmt.executeQuery("SELECT*FROM user"); } catch (Exception e) { System.out.println(e); } setTitle("登陆页面"); JPanel panel = new JPanel(); //JLabel lblName = new JLabel("用户名:"); JTextField txtName = new JTextField(10); //lblName.setHorizontalAlignment(JLabel.CENTER); panel.add(new JLabel("用户名:")); panel.add(txtName); JLabel lblPassword = new JLabel("密码:"); JPasswordField txtPassword = new JPasswordField(10); lblPassword.setHorizontalAlignment(JLabel.CENTER); panel.add(lblPassword); panel.add(txtPassword); add(panel, BorderLayout.CENTER); JPanel panel2 = new JPanel(); JButton btnLogin = new JButton("登陆"); /** * 给登陆按钮添加监听事件 当按钮被点击时时间被触发 */ btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean b = false; // boolean b = um.Login(txtName.getText(), txtPassword.getText()); try { stmt = conn.createStatement();// 预定义语句 // 数据库查询语句(根据用户名和密码) String sql = "select * from user where User='" + txtName.getText() + "' and Password='" + txtPassword.getText() + "'"; rst = stmt.executeQuery(sql);// 执行查询语句 // rst中有数据,则将标记改为true if (rst.next()) { b = true; } } catch (SQLException e1) { e1.printStackTrace(); } if (b) {// 登陆成功,跳转页面 JOptionPane.showMessageDialog(null, "登陆成功!"); new ProductQueryDemo();// 打开主页 dispose();// 关闭窗口 } else {// 登陆失败 JOptionPane.showMessageDialog(null, "登陆失败!"); } } }); JButton btnReset = new JButton("重置"); /** * 点击重置按钮时,将文本框中的值设置为空 */ btnReset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { txtName.setText(""); txtPassword.setText(""); } }); JButton btnSignin = new JButton("注册"); /** * 点击注册按钮时,调用注册程序 */ btnSignin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new Signin(); dispose();// 关闭窗口 } }); panel2.add(btnLogin); panel2.add(btnReset); panel2.add(btnSignin); add(panel2, BorderLayout.PAGE_END); setSize(430, 150); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new Login(); } }
### 回答1: java.sql.SQLException: 结果集已耗尽是一个JDBC异常,表示已经遍历完了结果集中的所有数据。 当使用JDBC从数据库中查询数据时,查询结果会以结果集的形式返回给应用程序。结果集是一个类似表格的结构,包含了一系列的记录和字段。 当我们向结果集中读取数据时,使用next()方法将指针移动到下一行,并返回一个布尔值,表示下一行是否存在。如果存在,我们可以获取该行的数据。如果不存在,即遍历完了整个结果集,将抛出java.sql.SQLException: 结果集已耗尽异常。 这个异常通常出现在以下情况下: 1. 当使用ResultSet对象从数据库中读取数据时,读取到最后一行,然后再次调用next()方法。 2. 当在一个ResultSet对象读取数据时,将ResultSet对象传递给其他方法或者其他线程,而这个ResultSet对象已经遍历完了所有数据。 3. 当使用同一个Statement对象执行多个查询语句时,如果没有使用close()方法显式关闭ResultSet对象,那么当执行下一个查询时,结果集已经被耗尽。 为了避免java.sql.SQLException: 结果集已耗尽异常,我们可以在使用ResultSet对象之后,及时关闭ResultSet、Statement和Connection对象,以释放资源。同时,在使用ResultSet对象之前,也可以先调用next()方法检查是否存在下一行数据,避免无法读取数据时抛出异常。 总之,java.sql.SQLException: 结果集已耗尽异常表示已经读取完了结果集中的数据,可通过关闭ResultSet、Statement和Connection对象以及在使用ResultSet之前检查是否存在下一行数据来避免该异常的发生。 ### 回答2: java.sql.SQLException: 结果集已耗尽是指在使用 JDBC 进行数据库查询时,结果集已经被遍历完毕,没有更多的数据可供访问。 当使用 ResultSet 对象获取数据库查询的结果集时,通常会使用 next() 方法来判断是否还有更多的数据行可供读取。如果 next() 方法返回 false,即表示结果集已经到达末尾。 出现 ResultSet exhausted 的原因可能有以下几种情况: 1. 结果集已经被完全遍历:通过在循环中使用 next() 方法遍历结果集时,如果没有在循环中提前退出或跳出循环,可能导致结果集被完全遍历。 示例代码如下: ```java ResultSet rs = statement.executeQuery("SELECT * FROM table_name"); while (rs.next()) { // 遍历结果集的每一行数据 // ... } // 循环结束后,结果集已经耗尽 ``` 2. 结果集使用完毕后未关闭:使用完 ResultSet 对象后,应该及时调用 close() 方法关闭结果集,以释放相关资源。 示例代码如下: ```java ResultSet rs = statement.executeQuery("SELECT * FROM table_name"); // 处理结果集数据 // ... rs.close(); // 关闭结果集 ``` 3. 结果集在查询语句执行后未立即访问:某些情况下,当查询语句执行后,如果不立即访问结果集,而是先执行其他操作,可能导致结果集耗尽。 示例代码如下: ```java ResultSet rs = statement.executeQuery("SELECT * FROM table_name"); // 其他业务逻辑处理 // ... while (rs.next()) { // 访问结果集数据 // ... } ``` 为避免出现结果集已耗尽的异常,应该在使用 ResultSet 对象时及时关闭结果集,并在执行查询后立即访问结果集。另外,也可以通过判断结果集的元数据(例如列数、列类型等)来确定是否有数据可供读取。 ### 回答3: java.sql.SQLException: 结果集已耗尽,是指在使用Java程序连接数据库,并且执行SQL查询语句后,尝试获取结果集中的下一行数据时,但是结果集已经没有更多的数据可供获取,此时程序会抛出此异常。 这种情况通常发生在以下几种情况下: 1. 在使用游标(ResultSet)遍历结果集时,已经遍历到结果集的最后一行,再次调用next()方法获取下一行数据时,就会出现该异常。 2. 在使用游标(ResultSet)遍历结果集时,再次调用next()方法获取下一行数据时,结果集已经被其他操作关闭了,导致结果集不可访问,此时也会抛出该异常。 3. 在使用游标(ResultSet)遍历结果集时,结果集的大小与代码逻辑不符合,比如结果集本应该有5行数据,但是已经提前遍历到了第6行,再次获取数据时就会出现该异常。 要解决这个问题,可以采取以下措施: 1. 在使用游标遍历结果集时,使用if语句判断是否还有下一行数据,避免出现结果集已耗尽的情况。如: while(resultSet.next()){ // 获取数据 } 2. 在多线程环境下,对于可能会关闭结果集的操作,需要进行合适的同步处理,避免在其他线程中关闭结果集时,当前线程还在尝试获取数据。 3. 检查代码逻辑,确保结果集的大小与代码中对结果集的操作一致,避免出现不一致的情况。 总结:当出现java.sql.SQLException: 结果集已耗尽的异常时,说明在操作结果集时,结果集已经没有更多的数据可供获取了。解决该问题可以通过合理的代码逻辑和对结果集的判断,避免出现该异常。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值