public static int addStudy(Study study) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO study (name,description,creatorEmail, dateCreated, " + "question, imageURL, requestedParticipants, numOfParticipants, status) " + "VALUES (?,?,?,?,?,?,?,?,?)"; try { ps = connection.prepareStatement(query); ps.setString(1, study.getName()); ps.setString(2, study.getDescription()); ps.setString(3, study.getCreatorEmail()); ps.setTimestamp(4, study.getDateCreated()); ps.setString(5, study.getQuestion()); ps.setString(6, study.getImageURL()); ps.setInt(7, study.getRequestedParticipants()); ps.setInt(8, study.getNumOfParticipants()); ps.setString(9, study.getStatus()); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } }
public java.util.List<AreaOfInterest> getAll() throws DataException { // get a jdbc connection Connection conn = cp.get(); LinkedList<AreaOfInterest> areas = new LinkedList(); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("SELECT guid FROM areaOfInterest"); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String myGuid = rs.getString("guid"); AreaOfInterest a; try { a = read(myGuid, conn); } catch (Exception ex) { throw new DataException("bad read areas"); } areas.add(a); } } catch (SQLException ex) { throw new DataException("bad read all areas"); } finally { cp.release(conn); } return areas; }
/** * Checks if the pool item is still valid. * * @return true if the pool item is valid, false if it should be removed. */ boolean isValid() { synchronized (this) { long now = Alarm.getCurrentTime(); long maxIdleTime = _cm.getMaxIdleTime(); long maxPoolTime = _cm.getMaxPoolTime(); long maxActiveTime = _cm.getMaxActiveTime(); boolean isActive = isActive() || _xid != null; boolean isDead = false; if (!isActive && _hasConnectionError) { isDead = true; log.fine("closing pool item from connection error:" + this); } else if (!isActive && 0 < maxIdleTime && _poolEventTime + maxIdleTime < now) { isDead = true; log.fine("closing pool item from idle timeout:" + this); } else if (!isActive && 0 < maxPoolTime && _poolStartTime + maxPoolTime < now) { isDead = true; log.fine("closing pool item from pool timeout:" + this); } else if (isActive && 0 < maxActiveTime && _poolEventTime + maxActiveTime < now) { isDead = true; log.warning("closing pool item from active timeout:" + this); } if (isDead) { _hasConnectionError = true; return false; } else return true; } }
public static int updateStudy(String code, Study study) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "UPDATE study SET " + "name = ?, description = ?, question = ? , imageURL = ?, requestedParticipants = ?," + "numOfParticipants = ?, status = ?" + "WHERE code = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, study.getName()); ps.setString(2, study.getDescription()); ps.setString(3, study.getQuestion()); ps.setString(4, study.getImageURL()); ps.setInt(5, study.getRequestedParticipants()); ps.setInt(6, study.getNumOfParticipants()); ps.setString(7, study.getStatus()); ps.setString(8, code); return ps.executeUpdate(); } catch (SQLException e) { System.out.println(e); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } }
@Override public boolean closeConnection(String connectionIdentifier, JID peer) { final String outID = toConnectionIDToken(connectionIdentifier, OUT, peer); final String inID = toConnectionIDToken(connectionIdentifier, IN, peer); final IByteStreamConnection out = connectionPool.remove(outID); final IByteStreamConnection in = connectionPool.remove(inID); boolean closed = false; if (out != null) { closed |= true; out.close(); LOG.debug("closed connection [pool id=" + outID + "]: " + out); } if (in != null) { closed |= true; in.close(); LOG.debug("closed connection [pool id=" + inID + "]: " + in); } return closed; }
public static List<Departamento> buscarDepartamentos() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); CallableStatement cs = null; ResultSet rs = null; try { List<Departamento> departamentos = new ArrayList(); cs = connection.prepareCall("{ call listaDepartamento() }"); rs = cs.executeQuery(); while (rs.next()) { Departamento dpo = new Departamento(rs.getInt("idDepartamento"), rs.getString("nombreDepartamento")); departamentos.add(dpo); } return departamentos; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closeStatement(cs); pool.freeConnection(connection); } }
public static List<Pago> buscarPagos() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); CallableStatement cs = null; ResultSet rs = null; try { List<Pago> pagos = new ArrayList(); cs = connection.prepareCall("{ call listaPago() }"); rs = cs.executeQuery(); while (rs.next()) { Pago pag = new Pago(rs.getInt("idMetodoPago"), rs.getString("nombreMetodoPago")); pagos.add(pag); } return pagos; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closeStatement(cs); pool.freeConnection(connection); } }
public static List<Sucursal> buscarSucursales() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); CallableStatement cs = null; ResultSet rs = null; try { List<Sucursal> sucursales = new ArrayList(); cs = connection.prepareCall("{ call listaSucursal() }"); rs = cs.executeQuery(); while (rs.next()) { Sucursal suc = new Sucursal(rs.getInt("idSucursal"), rs.getString("nombreSucursal")); sucursales.add(suc); } return sucursales; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closeStatement(cs); pool.freeConnection(connection); } }
public void purgeConnections() { synchronized (connectionPools) { for (ConnectionPool cp : connectionPools.values()) { cp.purgeConnections(); } } }
/** Returns the XA resource. */ void enableLocalTransactionOptimization(boolean enableOptimization) { if (_xaResource == null) _isXATransaction = false; else if (_localTransaction == null) _isXATransaction = true; else if (!_cm.isLocalTransactionOptimization()) _isXATransaction = true; else if (!_cm.isShareable()) _isXATransaction = true; else _isXATransaction = !enableOptimization; }
public boolean addFriendConnection(String user1, String user2) { String insert_into_table = "INSERT INTO " + Constant.FRIENDS_TABLE + " (userid, friendid) " + "VALUES (?, ?)"; // insert_into_table = "insert into friends (userid,friendid) values (2,3)"; try { Connection con = cp.getConnectionFromPool(); System.out.println("here1"); // get userid's from usernames int user_id = getUserId(con, user1); // get id from user1 System.out.println("here2"); int friend_id = getUserId(con, user2); // get id from user2 PreparedStatement ps = con.prepareStatement(insert_into_table); ps.setInt(1, user_id); ps.setInt(2, friend_id); System.out.println("here3"); // PreparedStatement ps = con.prepareStatement(insert_into_table); if (user_id != 0 && friend_id != 0) ps.executeUpdate(); cp.returnConnectionToPool(con); } catch (SQLException e) { System.out.println("Friend SQL Exception"); } catch (Exception e) { System.out.println("Friend Other Exception"); } return true; }
public static List<Usuario> buscarUsuarios() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); CallableStatement cs = null; ResultSet rs = null; try { List<Usuario> usuas = new ArrayList(); cs = connection.prepareCall("{ call cajeroReporte() }"); rs = cs.executeQuery(); while (rs.next()) { Usuario usa = new Usuario( rs.getString("nombreUsuario"), rs.getString("apellidoPaterno"), rs.getInt("idUsuario")); usuas.add(usa); } return usuas; } catch (Exception ex) { ex.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closeStatement(cs); pool.freeConnection(connection); } }
/** * Creates a connection pool (2 connections) and execututes queries on each. It then tries to get * a third connection. */ public static void testConnectionPooling() { ConnectionPool conPool = new ConnectionPool(2, driverName, connURL, username, password); conPool.resizeConnectionPool(3); String out = ""; try { SQLExecutor sqlExec1 = new SQLExecutor(conPool); SQLResults res1 = sqlExec1.runQuery("select dd * from JDBC_TEST where CODE < 'E'"); res1.setToStringFormatWidth(11); out += res1.toString() + "\n\n"; SQLExecutor sqlExec2 = new SQLExecutor(conPool); SQLResults res2 = sqlExec2.runQuery("select * from JDBC_TEST where CODE > 'E'"); out += res2.toString() + "\n\n"; // try to get a third connection via getConnection(). there are no available // connections so the ConnectionPool will create a new connection, add it the // pool, and return the new connection SQLExecutor sqlExec3 = new SQLExecutor(conPool); SQLResults res3 = sqlExec2.runQuery("select * from JDBC_TEST where CODE > 'E'"); out += res3.toString(); } finally { conPool.closeAllConnections(); } System.out.println(out); }
public static int insertarVenta(Venta v) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); CallableStatement cs = null; ResultSet rs = null; Venta ven = null; try { cs = connection.prepareCall("{ call insertVenta(?, ?, ?, ?) }"); cs.setInt(1, v.getUsuarioVenta().getId()); cs.setDouble(2, v.getSubtotal()); cs.setInt(3, v.getPagoVenta().getIdPago()); cs.setInt(4, v.getUsuarioVenta().getSucursal().getIdSucursal()); rs = cs.executeQuery(); while (rs.next()) { ven = new Venta(rs.getInt("idVenta")); } return ven.getIdVenta(); } catch (Exception ex) { ex.printStackTrace(); return 0; } finally { DBUtil.closeStatement(cs); pool.freeConnection(connection); } }
public static void main(String[] args) { if (!ApplicationFields.setUpApplicationUtils()) { return; } ConnectionPool pool = new ConnectionPool(); pool.start(); }
public UserInfo getUser(String username) { UserInfo user = null; ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = connection.prepareStatement("select * from user_info where username=?"); ps.setString(1, username); rs = ps.executeQuery(); if (rs.next()) { user = new UserInfo(); user.setFirstName(rs.getString("firstName")); user.setLastName(rs.getString("lastName")); user.setAddress(rs.getString("address")); user.setAffiliation(rs.getString("affiliation")); user.setMemDur(rs.getString("memDur")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setCardType(rs.getString("cardType")); user.setCardNumber(rs.getString("cardNumber")); user.setCardNumber(rs.getString("email")); } } catch (Exception e) { System.out.println(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } return user; }
/** * Returns the current connection for the remote side. If the local side is connected to the * remote side as well as the remote side is connected to the local side the local to remote * connection will be returned. * * @param connectionID identifier for the connection to retrieve or <code>null</code> to retrieve * the default one * @param jid JID of the remote side * @return the connection to the remote side or <code>null</code> if no connection exists */ private IByteStreamConnection getCurrentConnection(String connectionID, JID jid) { IByteStreamConnection connection; connection = connectionPool.get(toConnectionIDToken(connectionID, OUT, jid)); if (connection != null) return connection; return connectionPool.get(toConnectionIDToken(connectionID, IN, jid)); }
@Test public void inUseConnectionsNotEvicted() throws Exception { ConnectionPool pool = new ConnectionPool(1, 100L, TimeUnit.NANOSECONDS); pool.setCleanupRunnableForTest(emptyRunnable); RealConnection c1 = new RealConnection(routeA1); c1.allocationCount = 1; c1.idleAtNanos = 50L; c1.socket = new Socket(); assertFalse(c1.socket.isClosed()); pool.put(c1); // Running at time 50, the pool returns that nothing can be evicted until time 150. assertEquals(100L, pool.cleanup(50L)); assertEquals(1, pool.getConnectionCount()); assertFalse(c1.socket.isClosed()); // Running at time 60, the pool returns that nothing can be evicted until time 160. assertEquals(100L, pool.cleanup(60L)); assertEquals(1, pool.getConnectionCount()); assertFalse(c1.socket.isClosed()); // Running at time 160, the pool returns that nothing can be evicted until time 260. assertEquals(100L, pool.cleanup(160L)); assertEquals(1, pool.getConnectionCount()); assertFalse(c1.socket.isClosed()); }
private void closeConnections() { synchronized (pools) { Enumeration elems = pools.keys(); while (elems.hasMoreElements() && timeToRun) { Object key = elems.nextElement(); ConnectionPool pool = (ConnectionPool) pools.get(key); printInfo(pool, key); pool.closeConnections(); } } }
// Returns all existing coupons of a certain type @Override public Collection<Coupon> getCouponByType(CouponType couponType) throws WaitingForConnectionInterrupted, ClosedConnectionStatementCreationException, ConnectionCloseException { // Establish connection Connection connection; try { connection = pool.getConnection(); } catch (GetConnectionWaitInteruptedException e) { throw new WaitingForConnectionInterrupted(); } // Prepare ArrayList to return ArrayList<Coupon> allCouponsFound = null; // Prepare and execute statement PreparedStatement statement = null; ResultSet couponsFound = null; // Prepare sql request String sqlRequest; try { sqlRequest = "SELECT * FROM APP.COUPON WHERE COUPON_TYPE='" + couponType + "'"; statement = connection.prepareStatement(sqlRequest); // Get all coupons in a ResultSet couponsFound = statement.executeQuery(); // Prepare Collection allCouponsFound = new ArrayList<Coupon>(); // Move all coupons from ResultSet to an ArrayList while (couponsFound.next()) { // Prepare temp coupon Coupon tempCoupon = new Coupon(); tempCoupon.setId(couponsFound.getLong("ID")); tempCoupon.setTitle(couponsFound.getString("TITLE")); tempCoupon.setStartDate(couponsFound.getDate("START_DATE")); tempCoupon.setEndDate(couponsFound.getDate("END_DATE")); tempCoupon.setAmount(couponsFound.getInt("AMOUNT")); tempCoupon.setType(CouponType.valueOf(couponsFound.getString("COUPON_TYPE"))); tempCoupon.setMessage(couponsFound.getString("MESSAGE")); tempCoupon.setPrice(couponsFound.getDouble("PRICE")); // Add coupon to the Collection allCouponsFound.add(tempCoupon); } } catch (SQLException e) { throw new ClosedConnectionStatementCreationException(); } // Close connections try { couponsFound.close(); statement.close(); } catch (SQLException e) { throw new ConnectionCloseException(); } pool.returnConnection(connection); // returns NULL, when no coupons found return allCouponsFound; }
public synchronized void delete() { // Drop main table and any other tables with the main table prefix // First get a list of the tables to drop ArrayList<String> tablesToDrop = new ArrayList<String>(); Connection con; try { con = connectionPool.getConnection(); } catch (ConnectionException e) { throw new BeanFactoryException(e); } try { Statement stmt = con.createStatement(); if (printSQL != null) printDebug("deleteTable: SHOW TABLES"); ResultSet rs = stmt.executeQuery("SHOW TABLES"); while (rs.next()) { String s = rs.getString(1); if (File.separatorChar == '\\') { // It's windows...case insensitive matching String lower = s.toLowerCase(); if (lower.equalsIgnoreCase(tableName)) tablesToDrop.add(s); if (lower.startsWith(tableName.toLowerCase() + "_")) tablesToDrop.add(s); } else { // It's Unix...case counts if (s.equals(tableName)) tablesToDrop.add(s); if (s.startsWith(tableName + "_")) tablesToDrop.add(s); } } rs.close(); stmt.close(); for (String name : tablesToDrop) { stmt = con.createStatement(); String sql = "DROP TABLE " + name; if (printSQL != null) printDebug("deleteTable: " + sql); stmt.executeUpdate(sql); stmt.close(); } connectionPool.releaseConnection(con); } catch (SQLException e) { try { con.close(); } catch (SQLException e2) { } throw new BeanFactoryException(e); } }
public String toString() { if (_mConn != null) { return (getClass().getSimpleName() + "[" + _cm.getName() + "," + _id + "," + _mConn.getClass().getSimpleName() + "]"); } else { return (getClass().getSimpleName() + "[" + _cm.getName() + "," + _id + ",null]"); } }
public DataSource createMCSConnectionPool( MCSConnectionPoolConfiguration configuration, DataSource dataSource) throws RepositoryException { // Create and configure a Connection pool if there is one. if (configuration == null || !configuration.isEnabled()) { return dataSource; } int maxConnections = configuration.getMaxConnections(); int maxFreeConnections = configuration.getMaxFreeConnections(); // int optimalFreeConnections; int minFreeConnections = configuration.getMinFreeConnections(); int initialConnections = configuration.getInitialConnections(); boolean keepConnectionsAlive = configuration.isKeepAliveActive(); ConnectionPool connectionPool = new ConnectionPool(dataSource); if (keepConnectionsAlive) { connectionPool.setKeepConnectionsAlive(true); int connectionPollInterval = configuration.getKeepAlivePollInterval(); if (connectionPollInterval > 0) { connectionPool.setConnectionPollInterval(connectionPollInterval); } } connectionPool.setMaxConnections(maxConnections); connectionPool.setMaxFreeConnections(maxFreeConnections); // connectionPool.setOptimalFreeConnections (optimalFreeConnections); connectionPool.setMinFreeConnections(minFreeConnections); connectionPool.setInitialConnections(initialConnections); connectionPool.start(); return connectionPool; }
// Returns collection of all existing coupons @Override public Collection<Coupon> getAllCoupons() throws WaitingForConnectionInterrupted, ClosedConnectionStatementCreationException, ConnectionCloseException { // Establish db connection Connection connection; try { connection = pool.getConnection(); } catch (GetConnectionWaitInteruptedException e) { throw new WaitingForConnectionInterrupted(); } // Prepare and execute SELECT Statement statement; ArrayList<Coupon> coupons; ResultSet rs; try { statement = connection.createStatement(); coupons = new ArrayList<Coupon>(); String sql = "SELECT * FROM APP.COUPON "; rs = statement.executeQuery(sql); while (rs.next()) { Coupon coupon = new Coupon(); coupon.setAmount(rs.getInt("AMOUNT")); coupon.setType(CouponType.valueOf(rs.getString("COUPON_TYPE"))); coupon.setEndDate(rs.getDate("END_DATE")); coupon.setId(rs.getLong("ID")); coupon.setImage(rs.getString("IMAGE")); coupon.setMessage(rs.getString("MESSAGE")); coupon.setPrice(rs.getDouble("PRICE")); coupon.setTitle(rs.getString("TITLE")); coupon.setStartDate(rs.getDate("START_DATE")); coupons.add(coupon); // System.out.println(coupon.toString()); coupons.add(coupon); } } catch (SQLException e) { throw new ClosedConnectionStatementCreationException(); } // Close connections try { rs.close(); statement.close(); } catch (SQLException e) { throw new ConnectionCloseException(); } pool.returnConnection(connection); return coupons; }
/** * Returns a shallow copy of this OkHttpClient that uses the system-wide default for each field * that hasn't been explicitly configured. */ OkHttpClient copyWithDefaults() { OkHttpClient result = clone(); if (result.proxySelector == null) { result.proxySelector = ProxySelector.getDefault(); } if (result.cookieHandler == null) { result.cookieHandler = CookieHandler.getDefault(); } if (result.cache == null && result.cacheAdapter == null) { // TODO: drop support for the default response cache. ResponseCache defaultCache = ResponseCache.getDefault(); result.cacheAdapter = defaultCache != null ? new CacheAdapter(defaultCache) : null; } if (result.socketFactory == null) { result.socketFactory = SocketFactory.getDefault(); } if (result.sslSocketFactory == null) { result.sslSocketFactory = getDefaultSSLSocketFactory(); } if (result.hostnameVerifier == null) { result.hostnameVerifier = OkHostnameVerifier.INSTANCE; } if (result.authenticator == null) { result.authenticator = AuthenticatorAdapter.INSTANCE; } if (result.connectionPool == null) { result.connectionPool = ConnectionPool.getDefault(); } if (result.protocols == null) { result.protocols = Util.immutableList(Protocol.HTTP_2, Protocol.SPDY_3, Protocol.HTTP_1_1); } return result; }
/** Changes the state to idle. */ void toIdle() { if (_shareHead != null) return; else if (_xid != null || _isLocalTransaction) return; else if (_hasConnectionError) { destroy(); return; } UserTransactionImpl transaction = _transaction; _transaction = null; if (transaction != null) { try { transaction.delistPoolItem(this, XAResource.TMSUCCESS); } catch (Throwable e) { log.log(Level.FINE, e.toString(), e); } } _isLocalTransaction = false; if (log.isLoggable(Level.FINE)) log.fine("idle " + this); _poolEventTime = Alarm.getCurrentTime(); _cm.toIdle(this); }
public GoogleSQLTable( Class<B> beanClass, String tableName, String jdbcDriver, String jdbcURL, String user, String password, AbstractFactory<?>[] referencedFactories) { // Check for null values and throw here (it's less confusing for the caller) if (beanClass == null) throw new NullPointerException("beanClass"); if (tableName == null) throw new NullPointerException("tableName"); if (jdbcDriver == null) throw new NullPointerException("jdbcDriver"); if (jdbcURL == null) throw new NullPointerException("jdbcURL"); // User and password can be null this.beanClass = beanClass; this.tableName = tableName.toLowerCase(); this.referencedFactories = referencedFactories; try { connectionPool = ConnectionPool.getInstance(jdbcDriver, jdbcURL, user, password); } catch (ConnectionException e) { throw new BeanFactoryException(e); } }
/** * Consulta as fatos do prestador passado em um determinado periodo * * @param strCdContrato - o codigo do contrato do prestado do qual se deseja obter as fatos * @param strNumPeriodo - o periodo de referencia do qual se deseja obter os fatos * @return um array de fatos do prestador fornecido como paramentro */ public static final ResumoFato[] buscaResumoFato(String strCdContrato, String strNumPeriodo) throws Exception { Connection con = ConnectionPool.getConnection(); ResumoFato[] fatos = null; PreparedStatement pst; ResultSet rset; int qtdeFatos = 0; try { pst = con.prepareStatement(CONSULTA_RESUMO_FATO); pst.setString(1, strCdContrato); pst.setString(2, strNumPeriodo); pst.setString(3, strCdContrato); pst.setString(4, strNumPeriodo); pst.setString(5, strCdContrato); pst.setString(6, strNumPeriodo); pst.setString(7, strCdContrato); pst.setString(8, strNumPeriodo); pst.setString(9, strCdContrato); pst.setString(10, strNumPeriodo); rset = pst.executeQuery(); if (!rset.next()) { return null; } // if ( ! rset.next() ) do { qtdeFatos += 1; } while (rset.next()); System.out.println("qtdeFatos -> " + qtdeFatos); fatos = new ResumoFato[qtdeFatos]; rset = pst.executeQuery(); qtdeFatos = 0; while (rset.next()) { fatos[qtdeFatos] = montaResumoFato(rset); qtdeFatos++; } // while } catch (SQLException sqle) { sqle.printStackTrace(); throw new Exception( "Não foi possivel estabelecer conexão com a base de " + "dados.Erro:\n" + sqle.getMessage()); } finally { // catch() if (con != null) { con.close(); System.out.println("Fechou a conexao"); } // if } return fatos; } // buscaResumoFato()
public void close() { try { connPool.close(); } catch (Exception e) { xAuthLog.severe("Failed to close " + getDBMS() + " connection pool!", e); } }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get a connection ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); String sqlStatement = request.getParameter("sqlStatement"); String sqlResult = ""; try { // create a statement Statement statement = connection.createStatement(); // parse the SQL string sqlStatement = sqlStatement.trim(); if (sqlStatement.length() >= 6) { String sqlType = sqlStatement.substring(0, 6); if (sqlType.equalsIgnoreCase("select")) { // create the HTML for the result set ResultSet resultSet = statement.executeQuery(sqlStatement); sqlResult = SQLUtil.getHtmlTable(resultSet); resultSet.close(); } else { int i = statement.executeUpdate(sqlStatement); if (i == 0) { sqlResult = "<p>The statement executed successfully.</p>"; } else { // an INSERT, UPDATE, or DELETE statement sqlResult = "<p>The statement executed successfully.<br>" + i + " row(s) affected.</p>"; } } } statement.close(); connection.close(); } catch (SQLException e) { sqlResult = "<p>Error executing the SQL statement: <br>" + e.getMessage() + "</p>"; } finally { pool.freeConnection(connection); } HttpSession session = request.getSession(); session.setAttribute("sqlResult", sqlResult); session.setAttribute("sqlStatement", sqlStatement); String url = "/index.jsp"; getServletContext().getRequestDispatcher(url).forward(request, response); }