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

The following examples show how to use java.sql.Statement#getConnection() . 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: ResultSetEnumerable.java    From Quicksql with MIT License 6 votes vote down vote up
public void close() {
  ResultSet savedResultSet = resultSet;
  if (savedResultSet != null) {
    try {
      resultSet = null;
      final Statement statement = savedResultSet.getStatement();
      savedResultSet.close();
      if (statement != null) {
        final Connection connection = statement.getConnection();
        statement.close();
        if (connection != null) {
          connection.close();
        }
      }
    } catch (SQLException e) {
      // ignore
    }
  }
}
 
Example 2
Source File: ModelBasedResultSetIterator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether the connection is still open.
 * 
 * @return <code>true</code> if the connection is still open
 */
public boolean isConnectionOpen()
{
    if (_resultSet == null)
    {
        return false;
    }
    try
    {
        Statement  stmt = _resultSet.getStatement();
        Connection conn = stmt.getConnection();

        return !conn.isClosed();
    }
    catch (SQLException ex)
    {
        return false;
    }
}
 
Example 3
Source File: ModelBasedResultSetIterator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the resources (connection, statement, resultset).
 */
public void cleanUp()
{
    if (_cleanUpAfterFinish && (_resultSet != null))
    {
        Connection conn = null;
        try
        {
            Statement stmt = _resultSet.getStatement();

            conn = stmt.getConnection();

            // also closes the resultset
            _platform.closeStatement(stmt);
        }
        catch (SQLException ex)
        {
            // we ignore it
        }
        _platform.returnConnection(conn);
        _resultSet = null;
    }
}
 
Example 4
Source File: CollationTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
private void setUpTable(Statement s) throws SQLException {

    s.execute("CREATE TABLE CUSTOMER(ID INT, NAME VARCHAR(40), NAMECHAR CHAR(40))");
    
    Connection conn = s.getConnection();

    PreparedStatement ps = conn.prepareStatement("INSERT INTO CUSTOMER VALUES(?,?,?)");
    for (int i = 0; i < NAMES.length; i++)
    {
            ps.setInt(1, i);
            ps.setString(2, NAMES[i]);
            ps.setString(3, NAMES[i]);
            ps.executeUpdate();
    }

    s.execute("create table xmlTable (x xml)");
    s.executeUpdate("insert into xmlTable values(null)");

    s.execute("create table DERBY_2961 (ID INT  GENERATED ALWAYS AS " +
    		" IDENTITY PRIMARY KEY, V XML)");
    s.executeUpdate("insert into DERBY_2961(V) values(null)");
    
    conn.commit();
    ps.close();
}
 
Example 5
Source File: JDBCUtils.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
/**
 * Close connection
 * 
 * @param rs
 */
public static void close(ResultSet rs) {
	Statement st = null;
	Connection con = null;
	try {
		try {
			if (rs != null) {
				st = rs.getStatement();
				rs.close();
			}
		} finally {
			try {
				if (st != null) {
					con = st.getConnection();
					st.close();
				}
			} finally {
				if (con != null) {
					con.close();
				}
			}
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example 6
Source File: ResultSetEnumerable.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void close() {
  ResultSet savedResultSet = resultSet;
  if (savedResultSet != null) {
    try {
      resultSet = null;
      final Statement statement = savedResultSet.getStatement();
      savedResultSet.close();
      if (statement != null) {
        final Connection connection = statement.getConnection();
        statement.close();
        if (connection != null) {
          connection.close();
        }
      }
    } catch (SQLException e) {
      // ignore
    }
  }
}
 
Example 7
Source File: Features.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the (pooled) connection, including the statements of all dependencies.
 */
private void close() throws SQLException {
    /*
     * Only one of 'statement' and 'result' should be non-null. The connection should be closed
     * by the 'Features' instance having a non-null 'result' because it is the main one created
     * by 'Table.features(boolean)' method. The other 'Features' instances are dependencies.
     */
    if (statement != null) {
        statement.close();
    }
    final ResultSet r = result;
    if (r != null) {
        result = null;
        final Statement s = r.getStatement();
        try (Connection c = s.getConnection()) {
            r.close();      // Implied by s.close() according JDBC javadoc, but we are paranoiac.
            s.close();
            for (final Features dependency : dependencies) {
                dependency.close();
            }
        }
    }
}
 
Example 8
Source File: ModelBasedResultSetIterator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the resources (connection, statement, resultset).
 */
public void cleanUp()
{
    if (_cleanUpAfterFinish && (_resultSet != null))
    {
        Connection conn = null;
        try
        {
            Statement stmt = _resultSet.getStatement();

            conn = stmt.getConnection();

            // also closes the resultset
            _platform.closeStatement(stmt);
        }
        catch (SQLException ex)
        {
            // we ignore it
        }
        _platform.returnConnection(conn);
        _resultSet = null;
    }
}
 
Example 9
Source File: PostgreSqlUtil.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Extract the Large Object Input Stream from PostgreSQL
    *
    * @param resultSet
    *            the Result Set to extract the blob from
    * @param columnIndex
    *            the index of column
    * @return the Large Object Input Stream from PostgreSQL
    * @throws SQLException
    */
   public static InputStream getPostgreSqlnputStream(ResultSet resultSet,
    int columnIndex) throws SQLException {
InputStream in;
Statement statement = resultSet.getStatement();
Connection conn = statement.getConnection();

// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection) conn)
	.getLargeObjectAPI();
long oid = resultSet.getLong(columnIndex);

if (oid < 1) {
    return null;
}

LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

in = obj.getInputStream();
return in;
   }
 
Example 10
Source File: JdbcHelperImpl.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Nullable
private Connection safeGetConnection(Statement statement) {
    Connection connection = null;
    Class<?> type = statement.getClass();
    Boolean supported = isSupported(connectionSupported, type);
    if (supported == Boolean.FALSE) {
        return null;
    }

    try {
        connection = statement.getConnection();
        if (supported == null) {
            markSupported(connectionSupported, type);
        }
    } catch (SQLException e) {
        markNotSupported(connectionSupported, type, e);
    }

    return connection;
}
 
Example 11
Source File: PeerSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onQuery(
        final Span span,
        final Statement statement,
        final List<String> queries) throws SQLException {

    final Connection connection = statement.getConnection();
    final Peer url = parser.parse(connection.getMetaData().getURL());

    tag(span, PEER_HOSTNAME, url.getHostname());
    tag(span, PEER_PORT, url.getPort());
    tag(span, PEER_HOST_IPV4, url.getIpv4());
    tag(span, PEER_HOST_IPV6, url.getIpv6());
}
 
Example 12
Source File: DataSourceTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void assertStatementOK(String dsName, Connection conn, Statement s)
throws SQLException {

    // checks currently only implemented for embedded
    if (usingEmbedded())
    {
        SecurityCheck.assertSourceSecurity(s, "java.sql.Statement");
    }

    Connection c1 = s.getConnection();
    if (c1 != conn)
    {
        // with DerbyNetClient and any kind of DataSource, this goes wrong
        if (!usingDerbyNetClient() && (dsName.indexOf("DataSource") >= 0))
            fail ("incorrect connection object returned for Statement.getConnection()");
    }

    s.addBatch("insert into intTable values 1");
    s.addBatch("insert into intTable values 2,3");
    int[] states = s.executeBatch();
    if (states[0] != 1)
        fail ("invalid update count for first batch statement");
    if (states[1] != 2)
        fail ("invalid update count for second batch statement");

    ResultSet rs = s.executeQuery("VALUES 1");
    if (rs.getStatement() != s)
        fail ("incorrect Statement object returned for ResultSet.getStatement for " + dsName);
    rs.close();
    s.close();
}
 
Example 13
Source File: J2EEDataSourceTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private void assertStatementOK(String dsName, Connection conn, Statement s)
        throws SQLException {

    // checks currently only implemented for embedded 
    if (usingEmbedded())
    {
        SecurityCheck.assertSourceSecurity(s, "java.sql.Statement");
    }

    Connection c1 = s.getConnection();
    if (c1 != conn)
    {
        // with DerbyNetClient and any kind of DataSource, this goes wrong
        if (!usingDerbyNetClient() && (dsName.indexOf("DataSource") >= 0))
            fail ("incorrect connection object returned for Statement.getConnection()");
    }

    s.addBatch("insert into intTable values 1");
    s.addBatch("insert into intTable values 2,3");
    int[] states = s.executeBatch();
    if (states[0] != 1)
        fail ("invalid update count for first batch statement");
    if (states[1] != 2)
        fail ("invalid update count for second batch statement");

    ResultSet rs = s.executeQuery("VALUES 1");
    if (rs.getStatement() != s)
        fail ("incorrect Statement object returned for ResultSet.getStatement for " + dsName);
    rs.close();
    s.close();
}
 
Example 14
Source File: J2EEDataSourceTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void assertStatementOK(String dsName, Connection conn, Statement s)
throws SQLException {

    // checks currently only implemented for embedded 
    if (usingEmbedded())
    {
        SecurityCheck.assertSourceSecurity(s, "java.sql.Statement");
    }

    Connection c1 = s.getConnection();
    if (c1 != conn)
    {
        // with DerbyNetClient and any kind of DataSource, this goes wrong
        if (!usingDerbyNetClient() && (dsName.indexOf("DataSource") >= 0))
            fail ("incorrect connection object returned for Statement.getConnection()");
    }

    s.addBatch("insert into intTable values 1");
    s.addBatch("insert into intTable values 2,3");
    int[] states = s.executeBatch();
    if (states[0] != 1)
        fail ("invalid update count for first batch statement");
    if (states[1] != 2)
        fail ("invalid update count for second batch statement");

    ResultSet rs = s.executeQuery("VALUES 1");
    if (rs.getStatement() != s)
        fail ("incorrect Statement object returned for ResultSet.getStatement for " + dsName);
    rs.close();
    s.close();
}
 
Example 15
Source File: DatabaseUserSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onQuery(
        final Span span,
        final Statement statement,
        final List<String> queries) throws SQLException {

    final Connection connection = statement.getConnection();
    span.setTag(DB_USER, connection.getMetaData().getUserName());
}
 
Example 16
Source File: FutureUpdateExecuteCallback.java    From Oceanus with Apache License 2.0 5 votes vote down vote up
protected final Object doExecute(Statement statement, String sql,
		ExecuteCallback<Integer> callback) throws SQLException {
	Object result = null;
	Connection connection = statement.getConnection();
	try {
		result = callback.execute(statement, sql);
		if (trasaction == null) {
			if (!connection.getAutoCommit()) {
				connection.commit();
			}
		}
	} catch (SQLException e) {
		logger.error("execute update error!sql=" + sql, e);
		if (trasaction == null) {
			if (!connection.getAutoCommit()) {
				connection.rollback();
				if (logger.isDebugEnabled()) {
					logger.debug("transaction error!rollback for sql="
							+ sql);
				}
			}
		}
		
		throw e;
	} finally {
		if (trasaction == null){
			statement.close();
			
			// 这里是一个硬编码,判断connection类型,为了兼容旧版dao的连接池管理,不重复关闭connection
			if (!connection.getClass().getName().equals("com.bj58.spat.core.dbms.ConnectionWrapper")) {
				connection.close();
			}
		}
	}
	return result;
}
 
Example 17
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 18
Source File: Derby3650Test.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void initializeBlobTables(Statement stmt) 
    throws SQLException, IOException
{
    // BLOB TEST SETUP...........................................
    stmt.executeUpdate(
            "CREATE TABLE testBlob (id int, length int, c BLOB(2M))");

    Connection conn = stmt.getConnection();
    PreparedStatement ps = 
        conn.prepareStatement("INSERT INTO TestBlob VALUES(?,?,?)");

    // insert 4 rows into "left" blob of join: 
    //     (1, 40000, blob), (1, 40001, blob), 
    //     (2, 40002, blob), (2, 40003, blob)
    byte[] mybytes = new byte[40000];
    Arrays.fill(mybytes, (byte) 1);
    ps.setInt(  1, 1);
    ps.setInt(  2, 40000);
    ps.setBytes(3, mybytes);
    ps.executeUpdate();

    mybytes = new byte[40001];
    Arrays.fill(mybytes, (byte) 1);
    ps.setInt(  1, 1);
    ps.setInt(  2, 40001);
    ps.setBytes(3, mybytes);
    ps.executeUpdate();

    mybytes = new byte[40002];
    Arrays.fill(mybytes, (byte) 2);
    ps.setInt(  1, 2);
    ps.setInt(  2, 40002);
    ps.setBytes(3, mybytes);
    ps.executeUpdate();

    mybytes = new byte[40003];
    Arrays.fill(mybytes, (byte) 2);
    ps.setInt(  1, 2);
    ps.setInt(  2, 40003);
    ps.setBytes(3, mybytes);
    ps.executeUpdate();

    ps.close();

    // insert 4 rows into "right" table of join: 
    stmt.executeUpdate("CREATE TABLE jointab (id int)");
    stmt.executeUpdate("INSERT INTO jointab values(1)");
    stmt.executeUpdate("INSERT INTO jointab values(1)");
    stmt.executeUpdate("INSERT INTO jointab values(2)");
    stmt.executeUpdate("INSERT INTO jointab values(2)");

    stmt.executeUpdate(
        "CREATE TABLE testMultipleBlob (id int, length int, c BLOB(2M))");
    ps = conn.prepareStatement(
            "INSERT INTO testMultipleBlob VALUES(?,?,?)");

    for (int i = 0; i < 100; i++)
    {
        mybytes = new byte[40000 + i];
        Arrays.fill(mybytes, (byte) i);

        ps.setInt(  1, i);
        ps.setInt(  2, 40000 + i);
        ps.setBytes(3,mybytes);
        ps.executeUpdate();
    }
    ps.close();
    conn.commit();
}
 
Example 19
Source File: ImportExportLobTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static void loadData(Statement s) throws SQLException {

        s.executeUpdate("insert into books values " + 
                        "(1, 'book 1', 'clob 1'," +  
                        "cast(X'3743640ADE12337610' as blob))");
        // rows with empty strings. 
        s.executeUpdate("insert into books values " + 
                        "(2, 'book 2', 'clob 2',  cast (X'' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(3, 'book 3', '', cast(X'42' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(4, 'book 4', 'clob 4',  " + 
                        "cast (X'3233445578990122558820' as blob))");
        
        // rows with a null
        s.executeUpdate("insert into books values " + 
                        "(5, null, 'clob 5'," +  
                        "cast(X'3843640ADE12337610' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(6,  'book  6', null,  " + 
                        "cast(X'3843640ADE12337610' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(7,  'book  7',  'clob 7' , null)");
        s.executeUpdate("insert into books values " + 
                        "(8, '', null,  cast (X'3843640ADE12' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(9, 'book  9', null,  cast (X'' as blob))");
        
        // insert data that contains some delimiter characters 
        // ( "(x22) ,(x2C) %(x25) ;(x3B) , tab(9) LF(A) )
        s.executeUpdate("insert into books values " + 
                        "(10, 'book ;10', '%asdadasdasd'," + 
                        " cast (X'222C23B90A' as blob))");
        // !(x21) $(24)
        s.executeUpdate("insert into books values " + 
                        "(11, '212C3B24', '2422412221', " + 
                        "  cast (X'212421222C23B90A2124' as blob))");
        // insert some clob data with default char delimiter inside 
        // the data. It should get exported in double-delimiter format
        // when exporting to the main export file. 
        s.executeUpdate("insert into books values" +
                        "(12, 'Transaction Processing' , " +
                        "'This books covers \"Transaction\" \"processing\" concepts'"+
                        ",cast (X'144594322143423214ab35f2e54e' as blob))");
        s.executeUpdate("insert into books values" + 
                        "(13, 'effective java' ," +  
                        "'describes how to write \" quality java \" code', " +
                        "cast (X'124594322143423214ab35f2e34c' as blob))");

        // insert some more randomly genrated data.
        Connection conn = s.getConnection();
        String sql = "insert into books values(? , ? , ? , ?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        int blobSize = 0;
        int id = 14;
        for (int i = 0 ; i < 17 ; i++) {
            ps.setInt(1 , id++);
            ps.setString(2 , "book" +i);
            blobSize +=  1024 * i;
            int clobSize = 1024 * i;
            Reader reader = new LoopingAlphabetReader(clobSize);
            ps.setCharacterStream(3, reader, clobSize);
            InputStream stream = new LoopingAlphabetStream(blobSize);
            ps.setBinaryStream(4, stream, blobSize);
            ps.executeUpdate();

            if ((i % 10) == 0) 
                conn.commit();
        }

        ps.close();
        conn.commit();
    }
 
Example 20
Source File: ImportExportLobTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private static void loadData(Statement s) throws SQLException {

        s.executeUpdate("insert into books values " + 
                        "(1, 'book 1', 'clob 1'," +  
                        "cast(X'3743640ADE12337610' as blob))");
        // rows with empty strings. 
        s.executeUpdate("insert into books values " + 
                        "(2, 'book 2', 'clob 2',  cast (X'' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(3, 'book 3', '', cast(X'42' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(4, 'book 4', 'clob 4',  " + 
                        "cast (X'3233445578990122558820' as blob))");
        
        // rows with a null
        s.executeUpdate("insert into books values " + 
                        "(5, null, 'clob 5'," +  
                        "cast(X'3843640ADE12337610' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(6,  'book  6', null,  " + 
                        "cast(X'3843640ADE12337610' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(7,  'book  7',  'clob 7' , null)");
        s.executeUpdate("insert into books values " + 
                        "(8, '', null,  cast (X'3843640ADE12' as blob))");
        s.executeUpdate("insert into books values " + 
                        "(9, 'book  9', null,  cast (X'' as blob))");
        
        // insert data that contains some delimiter characters 
        // ( "(x22) ,(x2C) %(x25) ;(x3B) , tab(9) LF(A) )
        s.executeUpdate("insert into books values " + 
                        "(10, 'book ;10', '%asdadasdasd'," + 
                        " cast (X'222C23B90A' as blob))");
        // !(x21) $(24)
        s.executeUpdate("insert into books values " + 
                        "(11, '212C3B24', '2422412221', " + 
                        "  cast (X'212421222C23B90A2124' as blob))");
        // insert some clob data with default char delimiter inside 
        // the data. It should get exported in double-delimiter format
        // when exporting to the main export file. 
        s.executeUpdate("insert into books values" +
                        "(12, 'Transaction Processing' , " +
                        "'This books covers \"Transaction\" \"processing\" concepts'"+
                        ",cast (X'144594322143423214ab35f2e54e' as blob))");
        s.executeUpdate("insert into books values" + 
                        "(13, 'effective java' ," +  
                        "'describes how to write \" quality java \" code', " +
                        "cast (X'124594322143423214ab35f2e34c' as blob))");

        // insert some more randomly genrated data.
        Connection conn = s.getConnection();
        String sql = "insert into books values(? , ? , ? , ?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        int blobSize = 0;
        int id = 14;
        for (int i = 0 ; i < 17 ; i++) {
            ps.setInt(1 , id++);
            ps.setString(2 , "book" +i);
            blobSize +=  1024 * i;
            int clobSize = 1024 * i;
            Reader reader = new LoopingAlphabetReader(clobSize);
            ps.setCharacterStream(3, reader, clobSize);
            InputStream stream = new LoopingAlphabetStream(blobSize);
            ps.setBinaryStream(4, stream, blobSize);
            ps.executeUpdate();

            if ((i % 10) == 0) 
                conn.commit();
        }

        ps.close();
        conn.commit();
    }