java.sql.Statement Java Examples

The following examples show how to use java.sql.Statement. 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 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 #2
Source File: InListIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseTableAndIndexTableHaveRightScan() throws Exception {
    String index = generateUniqueName();
    String fullTableName = generateUniqueName();

    try (Connection conn = DriverManager.getConnection(getUrl())) {
        conn.setAutoCommit(true);
        try (Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE " + fullTableName + "(ID1 BIGINT NOT NULL, ID2 BIGINT NOT NULL, " +
                    "VAL1 BIGINT, VAL2 BIGINT CONSTRAINT PK PRIMARY KEY (ID1,ID2))");
            stmt.execute("CREATE INDEX " + index + " ON " + fullTableName + " (ID2, ID1) INCLUDE (VAL2)");
        }

        PreparedStatement preparedStmt = conn.prepareStatement("SELECT VAL2 FROM " + fullTableName +
                " WHERE (ID2, ID1) IN ((1, 1),(2, 2))");
        QueryPlan queryPlan = PhoenixRuntime.getOptimizedQueryPlan(preparedStmt);
        queryPlan.getTableRef().getTable().getType();
        assertTrue(queryPlan.getExplainPlan().toString().contains(ExplainTable.POINT_LOOKUP_ON_STRING));
    }
}
 
Example #3
Source File: GlobalHashIndexTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testCreateGlobalHashIndexForPrimaryKey() throws SQLException, StandardException {
  // Create a schema
  Connection conn = getConnection();
  Statement s = conn.createStatement();
  s.execute("create schema EMP");

  // Check for PARTITION BY COLUMN
  s.execute("create table EMP.PARTITIONTESTTABLE (ID int not null, "
      + " SECONDID int not null, THIRDID int not null, primary key (ID, SECONDID))"
      + " PARTITION BY COLUMN (ID)"+ getOverflowSuffix());
  
  s.execute("INSERT INTO EMP.PARTITIONTESTTABLE values(1,2,3)");
  s.execute("INSERT INTO EMP.PARTITIONTESTTABLE values(4,5,6)");
  s.execute("INSERT INTO EMP.PARTITIONTESTTABLE values(7,8,9)");

  AlterTableTest.checkIndexType("EMP", "PARTITIONTESTTABLE",
      GfxdConstants.LOCAL_HASH1_INDEX_TYPE, "ID", "SECONDID");

  String[][] expectedRows = { { "1", "2", "3" } };
  ResultSet rs = s.executeQuery("Select * from EMP.PARTITIONTESTTABLE "
      + "where id=1 and secondid=2");
  JDBC.assertFullResultSet(rs, expectedRows);
}
 
Example #4
Source File: CheckConstraintIT.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testAlterTableExistingDataViolatesConstraint() throws Exception {
    String tableName = "table4".toUpperCase();
    try(Statement s = conn.createStatement()){
        s.executeUpdate(format("create table %s ( "+
                "id int not null primary key, "+
                "i_gt int, "+
                "i_eq int, "+
                "i_lt int, "+
                "v_neq varchar(32), "+
                "v_in varchar(32))",tableName));
        s.executeUpdate(format("insert into %s values(1000, 200, 90, 79, 'ok', 'good1')",tableName));
        try{
            s.executeUpdate(format("alter table %s add constraint id_ge_ck check (id > 1000)",tableName));
            Assert.fail("Expected add or enable constraint exception");
        }catch(SQLException e){
            Assert.assertEquals("Expected failed attempt to add check constraint.","X0Y59",e.getSQLState());
        }
    }
}
 
Example #5
Source File: OnlineBackupTest1.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
void select(String tableName) throws SQLException {

	Statement s = conn.createStatement();
	ResultSet rs = s.executeQuery("SELECT ID, name from " +  
								  tableName + " order by id" );
	int count = 0;
	int id = 0;
	while(rs.next())
	{
		int tid = rs.getInt(1);
		String name = rs.getString(2);
			if(name.equals("skywalker" + id) && tid!= id)
		{
			logMessage("DATA IN THE TABLE IS NOT AS EXPECTED");
			logMessage("Got :ID=" +  tid + " Name=:" + name);
			logMessage("Expected: ID=" + id + "Name=" + "skywalker" + id );
		}

		id++;
		count++;
	}
          
	rs.close();
	s.close();
          conn.commit();
}
 
Example #6
Source File: GrantRevokeTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Assert that a user has select privilege on a given table / column
 * @param hasPrivilege whether or not the user has the privilege
 * @param user the user to check
 * @param schema the schema to check
 * @param table the table to check
 * @param columns the set of columns to check
 * @throws SQLException throws all exceptions
 */
public void assertSelectPrivilege(boolean hasPrivilege, String user, String schema, String table, String[] columns) throws SQLException{
  Connection c = openUserConnection(user);

  Statement s = c.createStatement();
  try {
      boolean b = s.execute("select " + columnListAsString(columns) + " from " + schema + "." + table);

        if (!hasPrivilege)
            fail("expected no SELECT permission on table");

  } catch (SQLException e) {
    if (!hasPrivilege) {
      assertSQLState("42502", e);
    } else {
      e.printStackTrace();
      fail("Unexpected lack of select privilege.");
    }
  }
    s.close();
  c.close();

  assertPrivilegeMetadata(hasPrivilege, "SELECT", user, schema, table, columns);
}
 
Example #7
Source File: GfxdSerialWanDUnit.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static Runnable startSender() {
  CacheSerializableRunnable receiverConf = new CacheSerializableRunnable(
      "Configurator") {
    @Override
    public void run2() throws CacheException {
      try {
        Connection conn = TestUtil.jdbcConn;
        Statement st = conn.createStatement();
        StringBuilder str = new StringBuilder();
        str.append("CALL SYS.START_GATEWAYSENDER ('SENDER1')");
        st.execute(str.toString());
      }
      catch (SQLException sqle) {
        throw GemFireXDRuntimeException.newRuntimeException(null, sqle);
      }
    }

  };
  return receiverConf;
}
 
Example #8
Source File: DeclareGlobalTempTableJavaTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
    * Test for delete where current of on temporary tables
    * 
    * @throws SQLException
    */
   public void testDeleteWhereCurrentOfOnGTT() throws SQLException {
       Statement s = createStatement();
       assertUpdateCount(s , 0 , "DECLARE GLOBAL TEMPORARY TABLE SESSION.t2(c21 int, c22 int) on commit delete rows not logged");
       assertUpdateCount(s , 1 , "insert into SESSION.t2 values(21, 1)");
       assertUpdateCount(s , 1 , "insert into SESSION.t2 values(22, 1)");
       ResultSet rs1 = s.executeQuery("select count(*) from SESSION.t2");
JDBC.assertSingleValueResultSet(rs1 , "2");
       PreparedStatement pStmt1 = prepareStatement("select c21 from session.t2 for update");
       ResultSet rs2 = pStmt1.executeQuery();
       rs2.next();
       PreparedStatement pStmt2 = prepareStatement("delete from session.t2 where current of "+ rs2.getCursorName());
       pStmt2.executeUpdate();
       rs1 = s.executeQuery("select * from SESSION.t2");
       rs1.next();
       assertEquals(22, rs1.getInt(1));
       assertEquals(1, rs1.getInt(2));
       rs2.next();
       pStmt2.executeUpdate();
       rs1 = s.executeQuery("select count(*) from SESSION.t2");
       rs1.next();
       assertEquals(0, rs1.getInt(1));
       rs2.close();
       assertUpdateCount(s , 0 , "DROP TABLE SESSION.t2");
   }
 
Example #9
Source File: H2TestJobDaoImpl.java    From chronos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void cleanupDb() {
  try {
    Connection conn = newConnection();
    for (String sql : new String[] {
        String.format("DROP TABLE IF EXISTS %s", testTableName),
        String.format("DROP TABLE IF EXISTS %s", jobRunTableName),
        String.format("DROP TABLE IF EXISTS %s", queueTableName),
        String.format("DROP TABLE IF EXISTS %s", jobTableName) }) {
      Statement stat = conn.createStatement();
      stat.execute(sql);
      stat.close();
    }
    conn.close();
  } catch (SQLException ex) {
    ex.printStackTrace(); // this one we swallow since db might not have cleaned up last time
  }
}
 
Example #10
Source File: DistributedSQLTestBase.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  try {
    final GemFireCacheImpl cache;
    if (GemFireStore.getBootedInstance() != null
        && (cache = Misc.getGemFireCacheNoThrow()) != null
        && GemFireXDUtils.getMyVMKind().isAccessorOrStore()) {
      Connection conn = TestUtil.getConnection();
      Statement stmt = conn.createStatement();
      // also GemFireXD specific objects; first gateway senders/listeners
      for (AsyncEventQueue queue : cache.getAsyncEventQueues()) {
        executeCleanup(stmt, "drop asynceventlistener if exists \"" + queue.getId()
            + '"');
      }
      for (GatewaySender sender : cache.getGatewaySenders()) {
        executeCleanup(stmt, "drop gatewaysender if exists \"" + sender.getId()
            + '"');
      }
    }
  } catch (Exception ex) {
    getLogWriter().error("unexpected exception in cleanup", ex);
  }
}
 
Example #11
Source File: SelectForUpdateInTransactionDUnit.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void executeSelectForUpdateQuery(final String sql,
    final boolean exception, final int isolationLevel) {
  try {
    final java.sql.Connection conn = TestUtil.getConnection();
    Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
        ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT);
    if (isolationLevel != Connection.TRANSACTION_NONE) {
      conn.setTransactionIsolation(isolationLevel);
    }
    stmt.execute(sql);
    ResultSet rs = stmt.getResultSet();
    while(rs.next()) {
    }
    if (exception) {
      stmt.close();
      conn.commit();
      fail("The execution should have thrown exception");
    }
    stmt.close();
    conn.commit();
  } catch (Exception e) {
    if (!exception) {
      fail("should have got exception");
    }
  }
}
 
Example #12
Source File: PhysDB.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Update the database for the "Village and Pillage" update, otherwise known as MineCraft 1.14.
 */
private void doUpdateVillageAndPillage() {
    Matcher versionCheck = Pattern.compile("\\d[.]\\d+").matcher(Bukkit.getVersion());
    if (!versionCheck.find()) {
        return;
    }
    int minorVersion = Integer.parseInt(versionCheck.group().substring(2));
    if (minorVersion >= 14) {
        Statement statement = null;
        try {
            statement = connection.createStatement();
            statement.executeUpdate("UPDATE " + prefix + "blocks SET name = 'OAK_SIGN' WHERE name = 'SIGN'");
            statement.executeUpdate("UPDATE " + prefix + "blocks SET name = 'OAK_WALL_SIGN' WHERE name = 'WALL_SIGN'");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 
Example #13
Source File: ServerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testInsertCreateNewCompositeUdt() throws Exception {
  try (Connection c = connect();
      Statement s = c.createStatement()) {
    boolean b = s.execute("create type mytype as (i int, j int)");
    assertFalse(b);
    b = s.execute("create table w (i int not null, j mytype)");
    assertFalse(b);
    int x = s.executeUpdate("insert into w "
        + "values (1, mytype(1, 1))");
    assertEquals(x, 1);

    try (ResultSet r = s.executeQuery("select * from w")) {
      assertTrue(r.next());
      assertEquals(r.getInt("i"), 1);
      assertArrayEquals(r.getObject("j", Struct.class).getAttributes(), new Object[] {1, 1});
      assertFalse(r.next());
    }
  }
}
 
Example #14
Source File: BaseDbHelper.java    From flyway-test-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Simple counter query to have simple test inside test methods.
 *
 * @return number of customer in database
 * @throws Exception
 */
public int countCustomer() throws Exception {
    int result = -1;

    try (Statement stmt = con.createStatement()) {
        String query = "select count(*) from Customer";

        try (ResultSet rs = stmt.executeQuery(query)) {
            rs.next();
            Long cnt = rs.getLong(1);
            result = cnt.intValue();
        }
    }

    return result;
}
 
Example #15
Source File: TGroupStatement.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
/**
 * 会调用setBaseStatement以关闭已有的Statement
 */
private Statement createStatementInternal(Connection conn, String sql, boolean isBatch) throws SQLException {
    Statement stmt;
    if (isBatch) {
        stmt = conn.createStatement();
    } else {
        int resultSetHoldability = this.resultSetHoldability;
        if (resultSetHoldability == -1) {// 未调用过setResultSetHoldability
            resultSetHoldability = conn.getHoldability();
        }
        stmt = conn.createStatement(this.resultSetType, this.resultSetConcurrency, resultSetHoldability);
    }

    setBaseStatement(stmt); // 会关闭已有的Statement
    stmt.setQueryTimeout(queryTimeout); // 这句也有可能抛出异常,放在最后
    stmt.setFetchSize(fetchSize);
    stmt.setMaxRows(maxRows);
    // 填充sql元信息
    if (stmt instanceof DataChannel) {
        ((DataChannel) stmt).fillMetaData(sqlMetaData);
    }
    return stmt;
}
 
Example #16
Source File: DistinctTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public void testBasicDistinct() throws SQLException {
  Statement s = createStatement();

  s.execute("create table userInt (u integer)");
  s.execute("insert into userInt values (123)");
  s.execute("insert into userInt values (123)");
  s.execute("insert into userInt values (456)");
  s.execute("insert into userInt values (null)");
  s.execute("create table sqlInt (i int not null)");
  s.execute("insert into sqlInt values(123)");

  assertRowCount(2, s.executeQuery("select distinct u from userInt where u is not null"));
  assertRowCount(3, s.executeQuery("select u from userInt where u is not null"));
  try {
    s.executeQuery("select distinct i from sqlInt where i = (select distinct u from userInt)");
  } catch (SQLException e) {
    assertSQLState("21000", e);
  }

  s.execute("drop table userInt");
  s.execute("drop table sqlInt");
  s.close();
}
 
Example #17
Source File: TestSqlPeriodPredicates.java    From evosql with Apache License 2.0 6 votes vote down vote up
public void setUp() throws Exception {
      super.setUp();
      conn = newConnection();

Statement stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE PUBLIC.emp IF EXISTS");
stmt.executeUpdate("CREATE TABLE PUBLIC.emp (emp_id INTEGER NOT NULL,name VARCHAR(30),salary DECIMAL(10,2),dept_id INTEGER,bus_start DATETIME NOT NULL,bus_end DATETIME NOT NULL);");

stmt.executeUpdate("insert into PUBLIC.emp (emp_id, name, salary, dept_id, bus_start, bus_end)"
	+"values"
	+"(1, 'Tom', 300000.00, 1, TIMESTAMP '2000-01-01 01:02:03', TIMESTAMP '2000-02-01 01:02:03'),"
	+"(2, 'Tom', 305000.00, 1, TIMESTAMP '2000-02-01 01:02:03', TIMESTAMP '2000-03-01 01:02:03'),"
	+"(3, 'Tom', 310000.00, 1, TIMESTAMP '2000-03-01 01:02:03', TIMESTAMP '2000-04-01 01:02:03')"
	+";");

stmt.close();
  }
 
Example #18
Source File: SURTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * DERBY-1481 - ResultSet.beforeFirst() gives protocol error on scrollable,
 * updatable result sets that are downgraded to read-only
 * 
 * Check that no exception is thrown when calling positioning methods on a
 * result set that has been downgraded to read-only.
 *
 */
public void testDowngradeToScrollReadOnly() throws SQLException {
    Statement s = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 
                                      ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery("select * from t1 order by b");

    // check that the ResultSet was downgraded
    assertWarning(rs.getWarnings(), 
            QUERY_NOT_QUALIFIED_FOR_UPDATABLE_RESULTSET);
    
    // call positioning methods
    rs.next();
    rs.next();
    rs.previous();
    rs.relative(1);
    rs.absolute(3);
    rs.relative(-1);
    rs.first();
    rs.last();
    rs.beforeFirst();
    rs.afterLast();
    
    // close result set and statement
    rs.close();
    s.close();
}
 
Example #19
Source File: EvictionByCriteriaTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Eviction already defined on HDFS table. Alter the table to add a foreign key constraint.
 */
public void testEvictIncomingWithAlterTableAddForeignKeyConstraint() throws Exception {
  setupConnection();

  Connection conn = jdbcConn;
  Statement stmt = conn.createStatement();

  stmt.execute("create hdfsstore hdfsdata namenode 'localhost' homedir '"
      + HDFS_DIR + "' QUEUEPERSISTENT true");
  
  stmt.execute("create table trade.customers (cid int not null, cust_name int, primary key (cid))  " + getOffHeapSuffix() + "  " 
      + "persistent hdfsstore (hdfsdata) "
      + "eviction by criteria ( cid > 5 ) EVICT INCOMING ");
  
  stmt.execute("create table trade.networth (netid int not null, cid int not null, cash decimal (30, 20), constraint netw_pk primary key (netid))  " + getOffHeapSuffix() + "  "
      + " persistent hdfsstore (hdfsdata)"
      + " eviction by criteria ( cash > 1000 ) EVICT INCOMING ");
  
  try {
    stmt.execute("alter table trade.networth add constraint " +
  	  "cust_newt_fk foreign key (cid) references trade.customers (cid)");
  } catch (SQLFeatureNotSupportedException e) {
    //Expected. Do nothing.
  }
}
 
Example #20
Source File: MultiStatementIT.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiStmtTempTable() throws SQLException
{
  Connection connection = getConnection();
  Statement statement = connection.createStatement();

  String entry = "success";
  statement.unwrap(SnowflakeStatement.class).setParameter(
      "MULTI_STATEMENT_COUNT", 2);
  statement.execute(
      "create or replace temporary table test_multi (cola string); insert into test_multi values ('" + entry + "')");
  // temporary table should persist outside of the above statement
  statement.unwrap(SnowflakeStatement.class).setParameter(
      "MULTI_STATEMENT_COUNT", 1);
  ResultSet rs = statement.executeQuery("select * from test_multi");
  rs.next();
  assertEquals(entry, rs.getString(1));

  statement.close();
  connection.close();
}
 
Example #21
Source File: Issue569Test.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testMysqlView() throws SQLException {

    Connection connection = DbHelper.getDbConnection(DbHelper.TargetDB.MYSQL);
    if (connection == null) { System.err.println("Db " + DbHelper.TargetDB.MYSQL + " not available"); return; }

    try {
        Statement st = connection.createStatement();
        
        st.executeUpdate("CREATE TABLE IF NOT EXISTS issue569( id bigint primary key, name varchar(256), version int ) ");
        try {
            st.executeUpdate("DROP VIEW issue569_v");
        } catch (Exception e) {}
        st.executeUpdate("CREATE OR REPLACE  VIEW issue569_v(id, name, nb) as SELECT id, name, count(*) as nb FROM issue569 group by id, name");
        st.executeUpdate("TRUNCATE issue569");
        st.executeUpdate("INSERT INTO issue569 VALUES(1, 'v1', 1), (2, 'v2', 2)");
        
        
        Crud<CrudTest.OnlyKey, Long> objectCrud =
                JdbcMapperFactory.newInstance()
                        .addColumnProperty("id", KeyProperty.DEFAULT)
                        .<CrudTest.OnlyKey, Long>crud(MyPojo.class, Long.class).table("issue569_v");

        // read
        assertEquals(new MyPojo(1, "v1", 1), objectCrud.read(connection, 1l));
        assertEquals(new MyPojo(2, "v2", 1), objectCrud.read(connection, 2l));

    } finally {
        connection.close();
    }
}
 
Example #22
Source File: H2StorageManager.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void initDatabaseAccess(Connection con) throws Exception {
    Statement stmt = con.createStatement();
    stmt.execute("SET REFERENTIAL_INTEGRITY FALSE");
    stmt.execute("CREATE ALIAS IF NOT EXISTS NOW_MILLIS FOR \"java.lang.System.currentTimeMillis\";");
    super.initDatabaseAccess(con);
}
 
Example #23
Source File: CsvBulkLoadToolIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlreadyExistsOutputPath() {
    String tableName = "TABLE9";
    String outputPath = "/tmp/output/tabl9";
    try {
        Statement stmt = conn.createStatement();
        stmt.execute("CREATE TABLE " + tableName + "(ID INTEGER NOT NULL PRIMARY KEY, "
                + "FIRST_NAME VARCHAR, LAST_NAME VARCHAR)");
        
        FileSystem fs = FileSystem.get(getUtility().getConfiguration());
        fs.create(new Path(outputPath));
        FSDataOutputStream outputStream = fs.create(new Path("/tmp/input9.csv"));
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.println("1,FirstName 1,LastName 1");
        printWriter.println("2,FirstName 2,LastName 2");
        printWriter.close();
        
        CsvBulkLoadTool csvBulkLoadTool = new CsvBulkLoadTool();
        csvBulkLoadTool.setConf(getUtility().getConfiguration());
        csvBulkLoadTool.run(new String[] {
            "--input", "/tmp/input9.csv",
            "--output", outputPath,
            "--table", tableName,
            "--zookeeper", zkQuorum });
        
        fail(String.format("Output path %s already exists. hence, should fail",outputPath));
    } catch (Exception ex) {
        assertTrue(ex instanceof FileAlreadyExistsException); 
    }
}
 
Example #24
Source File: HowToHandleExceptionActivity.java    From AndroidStudyDemo with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 比较完备的异常处理机制演示
 */
private void goodCodeDemo() throws ApplicatinException {
    OutputStreamWriter out = null;
    java.sql.Connection conn = null;
    try {
        out.write("");
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery(
                "select uid, name from user");
        while (rs.next()) {
            System.out.println("ID:" + rs.getString("uid") + ",姓名: " + rs.getString("name"));
        }
    } catch (SQLException sqlex) {
        System.out.println("警告:数据不完整");
        throw new ApplicatinException("读取数据时出现SQL错误", sqlex);
    } catch (IOException ioex) {
        throw new ApplicatinException("写入数据时出现IO错误", ioex);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqlex2) {
                System.err.printf(this.getClass().getName() + ".mymethod - 不能关闭数据库连接: " + sqlex2.toString());
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioex2) {
                System.err.printf(this.getClass().getName() + ".mymethod - 不能关闭文件输出流: " + ioex2.toString());
            }
        }
    }
}
 
Example #25
Source File: DatabaseMetaDataTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** Drop the objects needed for testing the UDT-related metadata methods */
private void dropObjectsForUDTTests() throws SQLException
{
    getConnection().setAutoCommit(false);
    Statement s = createStatement();

    s.execute( "drop table orders" );
    s.execute( "drop type price restrict" );

    commit();
    getConnection().setAutoCommit(true);
}
 
Example #26
Source File: JpversioningTestHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void cleanContentVersions() throws ApsSystemException {
	Connection conn = null;
	Statement stat = null;
	try {
		conn = this.getConnection();
		stat = conn.createStatement();
		stat.executeUpdate(DELETE_VERSIONS);
	} catch (Throwable t) {
		throw new ApsSystemException("Error cleaning content versions", t);
	} finally {
		closeDaoResources(null, stat, conn);
	}
}
 
Example #27
Source File: savepointJdbc30_JSR169.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void doConnectionSetSavepointUnnamed() throws Throwable
{
	Connection conn = DriverManager.getConnection("jdbc:default:connection");
	Savepoint s1 = conn.setSavepoint();
	Statement s = conn.createStatement();
	s.executeUpdate("insert into t2 values(1)");
	conn.rollback(s1);
}
 
Example #28
Source File: MySQLConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Statement optimizeStatement(Statement statement) throws SQLException {
	super.optimizeStatement(statement);
	
	switch (operationType) {
	case READ:
		statement.setFetchSize(Integer.MIN_VALUE);
		break;
	}

	return statement;
}
 
Example #29
Source File: UpdateCursorTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tests non covering index.
 * 
 * @throws SQLException
 */
public void testNonCoveringIndex() throws SQLException {
	PreparedStatement select;
	Statement update;
	ResultSet cursor;
	String cursorName;

	update = createStatement();
	select = prepareStatement("select c3, c2 from t1 where c3 > 125 and c1 > 0 for update");
	cursor = select.executeQuery(); // cursor is now open
	cursorName = cursor.getCursorName();

	for (int i = 0; i < (SIZE_OF_T1 / 2); i++) {
		assertEquals(cursor.next(), true);
		update.execute("update t1 set c3 = c3 + 25 where current of " + cursorName);
	}
	assertFalse(
			"Update using noncovering index failed! Still got rows.",
			cursor.next());

	cursor.close();
	select.close();

	/* see what we have in the table */
	select = prepareStatement("select c1, c3 from t1");
	cursor = select.executeQuery(); // cursor is now open
	for (int i = 0; i < SIZE_OF_T1; i++) {
		assertEquals(cursor.next(), true);
	}
	assertFalse(
			"Update using noncovering index failed! Got more rows.", cursor
					.next());

	select.close();
	cursor.close();

	rollback();
}
 
Example #30
Source File: DelegatingConnection.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@Override
public Statement createStatement() throws SQLException {
    checkOpen();
    try {
        final DelegatingStatement ds = new DelegatingStatement(this, connection.createStatement());
        initializeStatement(ds);
        return ds;
    } catch (final SQLException e) {
        handleException(e);
        return null;
    }
}