Java Code Examples for java.sql.Statement#isClosed()

The following examples show how to use java.sql.Statement#isClosed() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StatementFinalizer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@SuppressWarnings("null") // st is not null when used
@Override
public void closeInvoked() {
    while (!statements.isEmpty()) {
        StatementEntry ws = statements.remove(0);
        Statement st = ws.getStatement();
        boolean shallClose = false;
        try {
            shallClose = st!=null && (!st.isClosed());
            if (shallClose) {
                st.close();
            }
        } catch (Exception ignore) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to closed statement upon connection close.",ignore);
            }
        } finally {
            if (logCreationStack && shallClose) {
                log.warn("Statement created, but was not closed at:", ws.getAllocationStack());
            }
        }
    }
}
 
Example 2
Source File: DbUtils.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Closes JDBC statement and open ResultSet without throwing exception. If there is one it is just logged.
 */
public static void closeStatement(
                                   Statement statement ) {

    if (statement == null) {
        return;
    }
    try {
        boolean isClosed;
        try {
            isClosed = statement.isClosed();
        } catch (AbstractMethodError err) {
            isClosed = false; // no JavaSE 6-compatible driver
        }
        if ( !isClosed ) { // statemnt != null here
            statement.close();
        }
    } catch (SQLException e) {
        log.warn(getFullSqlException("Exception while closing SQL statement", e));
    }
}
 
Example 3
Source File: StorageManager.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method executes the provided statement over the connection. If there
 * is an error returns -1 otherwise it returns the output of the executeUpdate
 * method on the PreparedStatement class which reflects the number of changed
 * rows in the underlying table.
 * 
 * @param sql
 * @param connection
 * @return Number of effected rows or -1 if there is an error.
 */
@SuppressLint("NewApi")
public void executeCommand(String sql, Connection connection) {
	Statement stmt = null;
	try {
		stmt = connection.createStatement();
		stmt.execute(sql);
	}
	catch (SQLException error) {
	}
	finally {
		try {
			if (stmt != null && !stmt.isClosed())
				stmt.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
 
Example 4
Source File: BaseStorageDao.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public void closeStatement ( final Statement statement )
{
    try
    {
        if ( statement == null || statement.isClosed () )
        {
            return;
        }
        statement.close ();
    }
    catch ( final SQLException e )
    {
        logger.debug ( "Exception on closing statement", e );
    }
}
 
Example 5
Source File: Database.java    From EnchantmentsEnhance with GNU General Public License v3.0 5 votes vote down vote up
public void createTables() throws IOException, SQLException {
    URL resource = Resources.getResource(Main.class, "/tables.sql");
    String[] databaseStructure = Resources.toString(resource, Charsets.UTF_8).split(";");

    if (databaseStructure.length == 0) {
        return;
    }

    Statement statement = null;

    try {
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        for (String query : databaseStructure) {
            query = query.trim();

            if (query.isEmpty()) {
                continue;
            }

            statement.execute(query);
        }

        connection.commit();

    } finally {
        connection.setAutoCommit(true);

        if (statement != null && !statement.isClosed()) {
            statement.close();
        }
    }
}
 
Example 6
Source File: Link.java    From HongsCORE with MIT License 5 votes vote down vote up
/**
 * 关闭Statement
 * @param ps
 * @throws HongsException
 */
public void closeStatement(Statement ps)
  throws HongsException
{
  try
  {
    if (ps == null || ps.isClosed()) return;
    ps.close();
  }
  catch (SQLException ex)
  {
    throw new HongsException(0x1034, ex);
  }
}
 
Example 7
Source File: ImpalaMetadataTask.java    From envelope with Apache License 2.0 5 votes vote down vote up
private void executeQuery(String query) throws SQLException {
  Connection conn = getConnection();
  Statement stmt = conn.createStatement();
  try {
    stmt.execute(query);
  } finally {
    if (!stmt.isClosed()) {
      stmt.close();
    }
  }
}
 
Example 8
Source File: Database.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("UnstableApiUsage")
public void createTables() throws IOException, SQLException {
       URL resource = Resources.getResource(SkyWarsReloaded.class, "/tables.sql");
       String[] databaseStructure = Resources.toString(resource, Charsets.UTF_8).split(";");

       if (databaseStructure.length == 0) {
           return;
       }

       Statement statement = null;

       try {
           connection.setAutoCommit(false);
           statement = connection.createStatement();

           for (String query : databaseStructure) {
               query = query.trim();

               if (query.isEmpty()) {
                   continue;
               }

               statement.execute(query);
           }

           connection.commit();

       } finally {
           connection.setAutoCommit(true);

           if (statement != null && !statement.isClosed()) {
               statement.close();
           }
       }
   }
 
Example 9
Source File: Database.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
public void createTables() throws IOException, SQLException {
    URL resource = Resources.getResource(SkyWarsReloaded.class, "/tables.sql");
    String[] databaseStructure = Resources.toString(resource, Charsets.UTF_8).split(";");

    if (databaseStructure.length == 0) {
        return;
    }

    Statement statement = null;

    try {
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        for (String query : databaseStructure) {
            query = query.trim();

            if (query.isEmpty()) {
                continue;
            }

            statement.execute(query);
        }

        connection.commit();

    } finally {
        connection.setAutoCommit(true);

        if (statement != null && !statement.isClosed()) {
            statement.close();
        }
    }
}
 
Example 10
Source File: ManagedConnection.java    From cassandra-jdbc-wrapper with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void close() throws SQLException
{
	for (Statement statement : statements)
	{
		if (!statement.isClosed())
		{
			statement.close();
		}
	}
	pooledCassandraConnection.connectionClosed();
	pooledCassandraConnection = null;
	physicalConnection = null;
}
 
Example 11
Source File: SentryConfigTool.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
public void verifyRemoteQuery(String queryStr) throws Exception {
  Class.forName("org.apache.hive.jdbc.HiveDriver");
  Connection conn = DriverManager.getConnection(getJdbcURL(), getUser(),
      getPassWord());
  Statement stmt = conn.createStatement();
  if (!isSentryEnabledOnHiveServer(stmt)) {
    throw new IllegalStateException("Sentry is not enabled on HiveServer2");
  }
  stmt.execute("set " + HiveAuthzConf.HIVE_SENTRY_MOCK_COMPILATION + "=true");
  try {
    stmt.execute(queryStr);
  } catch (SQLException e) {
    String errMsg = e.getMessage();
    if (errMsg.contains(HiveAuthzConf.HIVE_SENTRY_MOCK_ERROR)) {
      System.out.println("User "
          + readConfig(stmt, HiveAuthzConf.HIVE_SENTRY_SUBJECT_NAME)
          + " has privileges to run the query");
      return;
    } else if (errMsg
        .contains(HiveAuthzConf.HIVE_SENTRY_PRIVILEGE_ERROR_MESSAGE)) {
      printMissingPerms(readConfig(stmt,
          HiveAuthzConf.HIVE_SENTRY_AUTH_ERRORS));
      throw e;
    } else {
      throw e;
    }
  } finally {
    if (!stmt.isClosed()) {
      stmt.close();
    }
    conn.close();
  }

}
 
Example 12
Source File: SnowflakeConnectionV1.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * Close the connection
 *
 * @throws SQLException failed to close the connection
 */
@Override
public void close() throws SQLException
{
  logger.debug(" public void close()");

  if (isClosed)
  {
    // No exception is raised even if the connection is closed.
    return;
  }

  isClosed = true;
  try
  {
    if (sfSession != null && sfSession.isSafeToClose())
    {
      sfSession.close();
      sfSession = null;
    }
    // make sure to close all created statements
    for (Statement stmt : openStatements)
    {
      if (stmt != null && !stmt.isClosed())
      {
        if (stmt.isWrapperFor(SnowflakeStatementV1.class))
        {
          stmt.unwrap(SnowflakeStatementV1.class).close(false);
        }
        else
        {
          stmt.close();
        }
      }
    }
    openStatements.clear();

  }
  catch (SFException ex)
  {
    throw new SnowflakeSQLException(
        ex.getCause(), ex.getSqlState(), ex.getVendorCode(), ex.getParams());
  }
}
 
Example 13
Source File: SWStatementTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreparedStatementConfig() throws SQLException {
    Statement statement = swConnection.createStatement();
    statement.cancel();
    statement.getUpdateCount();
    statement.setFetchDirection(1);
    statement.getFetchDirection();
    statement.getResultSetConcurrency();
    statement.getResultSetType();
    statement.isClosed();
    statement.setPoolable(false);
    statement.isPoolable();
    statement.getWarnings();
    statement.clearWarnings();
    statement.setCursorName("test");
    statement.setMaxFieldSize(11);
    statement.getMaxFieldSize();
    statement.setMaxRows(10);
    statement.getMaxRows();
    statement.setEscapeProcessing(true);
    statement.setFetchSize(1);
    statement.getFetchSize();
    statement.setQueryTimeout(1);
    statement.getQueryTimeout();
    Connection connection = statement.getConnection();

    statement.execute("SELECT * FROM test");
    statement.getMoreResults();
    statement.getMoreResults(1);
    statement.getResultSetHoldability();
    statement.getResultSet();

    statement.close();
    verify(mysqlStatement).getUpdateCount();
    verify(mysqlStatement).getMoreResults();
    verify(mysqlStatement).setFetchDirection(anyInt());
    verify(mysqlStatement).getFetchDirection();
    verify(mysqlStatement).getResultSetType();
    verify(mysqlStatement).isClosed();
    verify(mysqlStatement).setPoolable(anyBoolean());
    verify(mysqlStatement).getWarnings();
    verify(mysqlStatement).clearWarnings();
    verify(mysqlStatement).setCursorName(anyString());
    verify(mysqlStatement).setMaxFieldSize(anyInt());
    verify(mysqlStatement).getMaxFieldSize();
    verify(mysqlStatement).setMaxRows(anyInt());
    verify(mysqlStatement).getMaxRows();
    verify(mysqlStatement).setEscapeProcessing(anyBoolean());
    verify(mysqlStatement).getResultSetConcurrency();
    verify(mysqlStatement).getResultSetConcurrency();
    verify(mysqlStatement).getResultSetType();
    verify(mysqlStatement).getMoreResults(anyInt());
    verify(mysqlStatement).setFetchSize(anyInt());
    verify(mysqlStatement).getFetchSize();
    verify(mysqlStatement).getQueryTimeout();
    verify(mysqlStatement).setQueryTimeout(anyInt());
    verify(mysqlStatement).getResultSet();
    assertThat(connection, CoreMatchers.<Connection>is(swConnection));

    TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
    List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
    assertThat(spans.size(), is(1));
    assertDBSpan(spans.get(0), "Mysql/JDBI/Statement/execute", "SELECT * FROM test");
}
 
Example 14
Source File: Jdbc41Bridge.java    From Tomcat8-Source-Read with MIT License 3 votes vote down vote up
/**
 * Delegates to {@link Statement#isCloseOnCompletion()} without throwing a {@link AbstractMethodError}.
 * <p>
 * If the JDBC driver does not implement {@link Statement#isCloseOnCompletion()}, then just check that the
 * connection is closed to then throw an SQLException.
 * </p>
 *
 * @param statement
 *            See {@link Statement#isCloseOnCompletion()}
 * @return See {@link Statement#isCloseOnCompletion()}
 * @throws SQLException
 *             See {@link Statement#isCloseOnCompletion()}
 * @see Statement#closeOnCompletion()
 */
public static boolean isCloseOnCompletion(final Statement statement) throws SQLException {
    try {
        return statement.isCloseOnCompletion();
    } catch (final AbstractMethodError e) {
        if (statement.isClosed()) {
            throw new SQLException("Statement closed");
        }
        return false;
    }
}
 
Example 15
Source File: Jdbc41Bridge.java    From commons-dbcp with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates to {@link Statement#isCloseOnCompletion()} without throwing an {@link AbstractMethodError}.
 * <p>
 * If the JDBC driver does not implement {@link Statement#isCloseOnCompletion()}, then just check that the
 * connection is closed to then throw an SQLException.
 * </p>
 *
 * @param statement
 *            See {@link Statement#isCloseOnCompletion()}
 * @return See {@link Statement#isCloseOnCompletion()}
 * @throws SQLException
 *             See {@link Statement#isCloseOnCompletion()}
 * @see Statement#closeOnCompletion()
 */
public static boolean isCloseOnCompletion(final Statement statement) throws SQLException {
    try {
        return statement.isCloseOnCompletion();
    } catch (final AbstractMethodError e) {
        if (statement.isClosed()) {
            throw new SQLException("Statement closed");
        }
        return false;
    }
}
 
Example 16
Source File: Jdbc41Bridge.java    From commons-dbcp with Apache License 2.0 3 votes vote down vote up
/**
 * Delegates to {@link Statement#closeOnCompletion()} without throwing an {@link AbstractMethodError}.
 * <p>
 * If the JDBC driver does not implement {@link Statement#closeOnCompletion()}, then just check that the connection
 * is closed to then throw an SQLException.
 * </p>
 *
 * @param statement
 *            See {@link Statement#closeOnCompletion()}
 * @throws SQLException
 *             See {@link Statement#closeOnCompletion()}
 * @see Statement#closeOnCompletion()
 */
public static void closeOnCompletion(final Statement statement) throws SQLException {
    try {
        statement.closeOnCompletion();
    } catch (final AbstractMethodError e) {
        if (statement.isClosed()) {
            throw new SQLException("Statement closed");
        }
    }
}
 
Example 17
Source File: Jdbc41Bridge.java    From Tomcat8-Source-Read with MIT License 3 votes vote down vote up
/**
 * Delegates to {@link Statement#closeOnCompletion()} without throwing a {@link AbstractMethodError}.
 * <p>
 * If the JDBC driver does not implement {@link Statement#closeOnCompletion()}, then just check that the connection
 * is closed to then throw an SQLException.
 * </p>
 *
 * @param statement
 *            See {@link Statement#closeOnCompletion()}
 * @throws SQLException
 *             See {@link Statement#closeOnCompletion()}
 * @see Statement#closeOnCompletion()
 */
public static void closeOnCompletion(final Statement statement) throws SQLException {
    try {
        statement.closeOnCompletion();
    } catch (final AbstractMethodError e) {
        if (statement.isClosed()) {
            throw new SQLException("Statement closed");
        }
    }
}
 
Example 18
Source File: JdbcDatabaseManager.java    From logging-log4j2 with Apache License 2.0 2 votes vote down vote up
/**
 * Checks if a statement is closed. A null statement is considered closed.
 *
 * @param statement The statement to check.
 * @return true if a statement is closed, false if null.
 * @throws SQLException if a database access error occurs
 */
private boolean isClosed(final Statement statement) throws SQLException {
    return statement == null || statement.isClosed();
}