No operations allowed after statement closed

后端 未结 3 1969
逝去的感伤
逝去的感伤 2021-01-03 05:04

I am getting the Exception with the signature No operations allowed after statement closed. inside my Java code where I am trying to insert values into the data

3条回答
  •  我在风中等你
    2021-01-03 05:36

    Create a Utility class for connection management to manage it at single point in whole application.

    Don't load the DataSource every time you need a new connection.

    Sample code:

    public class ConnectionUtil {
    
        private DataSource dataSource;
    
        private static ConnectionUtil instance = new ConnectionUtil();
    
        private ConnectionUtil() {
            try {
                Context initContext = new InitialContext();
                dataSource = (DataSource) initContext.lookup("JNDI_LOOKUP_NAME");
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    
        public static ConnectionUtil getInstance() {
            return instance;
        }
    
        public Connection getConnection() throws SQLException {
            Connection connection = dataSource.getConnection();
            return connection;
        }
    
        public void close(Connection connection) throws SQLException {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
            connection = null;
        }
    
    }
    

    Always close the connection and handle it in try-catch-finally

            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                conn = ConnectionUtil.getInstance().getConnection();
    
                ...
            } finally {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    ConnectionUtil.getInstance().close(conn);
                }
            }
    

提交回复
热议问题