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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #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: 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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: JdbcDB.java    From quark with Apache License 2.0 5 votes vote down vote up
public ImmutableMap<String, Schema> getSchemas() throws QuarkException {
  Connection conn = null;
  Statement stmt = null;
  try {
    conn = this.getConnection();
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(this.getCatalogSql());
    ImmutableMap<String, Schema> schemaMap = getSchemaFromResultSet(rs, this.getTypes(conn));
    rs.close();
    return schemaMap;
  } catch (ClassNotFoundException | SQLException s) {
    throw new QuarkException(s);
  } finally {
    try {
      if (stmt != null) {
        stmt.close();
      }

      if (conn != null) {
        conn.close();
      }
    } catch (SQLException e) {
      LOG.error("Exception thrown while closing connection to "
          + this.url + " " + e.getMessage(), e);
    }
  }
}
 
Example #22
Source File: ProcedureTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Tests that <code>Statement.executeQuery()</code> fails when
 * multiple result sets are returned.
 * @exception SQLException if a database error occurs
 */
public void testExecuteQueryWithMoreThanOneDynamicResultSet()
    throws SQLException
{
    Statement stmt = createStatement();
    try {
        stmt.executeQuery("CALL RETRIEVE_DYNAMIC_RESULTS(2)");
        fail("executeQuery() didn't fail.");
    } catch (SQLException sqle) {
        assertMultipleResultsFromExecuteQuery(sqle);
    }
}
 
Example #23
Source File: PlumemoBlackListTable.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@Override
public void builderTable(final Statement stat) {
    try {
        stat.execute(createHelloBlogAuthUserLog());
        log.info("初始化plumemo_black_list完成");
    } catch (final SQLException e) {
        log.info("初始化plumemo_black_list失败", e);
    }
}
 
Example #24
Source File: JdbcRealTimeSink.java    From sylph with Apache License 2.0 5 votes vote down vote up
@Override
public void close(Throwable errorOrNull)
{
    try (Connection conn = connection) {
        try (Statement stmt = statement) {
            if (stmt != null) {
                this.flush();
            }
        }
    }
    catch (SQLException e) {
        logger.error("close connection fail", e);
    }
}
 
Example #25
Source File: ExceptionsWrapperTest.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
protected static void oneTimeTeardown() throws Exception {
    Session session = null;
    Statement stmt = null;
    try {
        session = HibernateFactory.getSession();
        stmt = session.connection().createStatement();
        Connection c = session.connection();
        forceQuery(c, "drop table exceptions_test");
        c.commit();
    }
    finally {
        HibernateHelper.cleanupDB(stmt);
    }
}
 
Example #26
Source File: NullableUniqueConstraintTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void tearDown() throws Exception {
    Connection con = getConnection();
    con.commit ();
    Statement stmt = con.createStatement();
    stmt.executeUpdate("drop table constraintest");
    stmt.close ();
    con.commit ();
    super.tearDown();
}
 
Example #27
Source File: DistinctTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public void testIdenticalRows() throws SQLException {
       Statement s = createStatement();
       s.execute("delete from t");
       s.execute("insert into t values (1, 2, 3, 4, '1992-01-01', '19:01:01', '1992-01-01 19:01:01.000', 'hello', 'planet')");
       s.execute("insert into t values (1, 2, 3, 4, '1992-01-01', '19:01:01', '1992-01-01 19:01:01.000', 'hello', 'planet')");
	
	int[] expectedRows = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 0,
			               0, 2, 0, 2, 2, 2, 0, -1, 1, 1, 1, 2, 2, 1,
			               2, 2, 1, 2, 1, 1, 1, 1 };
	
	checkDistinctRows(expectedRows);
       s.close();
}
 
Example #28
Source File: HerdDBDatabaseMetadata.java    From herddb with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE")
public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException {
    String query = "SELECT tablespace_name FROM SYSTABLESPACES";
    if (schemaPattern != null && !schemaPattern.isEmpty()) {
        query = query + " WHERE tablespace_name LIKE '" + SQLUtils.escape(schemaPattern) + "'";
    }

    try (Statement statement = con.createStatement();
         ResultSet rs = statement.executeQuery(query)) {

        List<Map<String, Object>> results = new ArrayList<>();
        while (rs.next()) {
            String tablespace_name = rs.getString("tablespace_name");

            Map<String, Object> data = new HashMap<>();

            data.put("TABLE_SCHEM", tablespace_name);
            data.put("TABLE_CATALOG", null);

            results.add(data);

        }
        ScanResultSetMetadata metadata = new ScanResultSetMetadata(GET_SCHEMAS_SCHEMA);
        return new HerdDBResultSet(new MapListScanResultSet(TransactionContext.NOTRANSACTION_ID, metadata, GET_SCHEMAS_SCHEMA, results));
    }
}
 
Example #29
Source File: TradeCustomersDMLDistTxStmt.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected void updateGfxdOnlyTable(Connection conn, int[] newCid, int[] cid, String[] cust_name,
    Date[] since, String[] addr, int[] whichUpdate, int size) {
  PreparedStatement stmt = null;
  Statement s = getStmt(conn);
  int tid = getMyTid();
  
  for (int i=0 ; i<size ; i++) {
    
    if (whichUpdate[i] == 0) {
      Log.getLogWriter().info("update partition key statement is " + update[whichUpdate[i]]);
      stmt = getUnsupportedStmt(conn, update[whichUpdate[i]]);
    }
    else {
      if (SQLTest.testPartitionBy) { //will be removed after bug #39913 is fixed
        stmt = getCorrectTxStmt(conn, whichUpdate[i]);
      } 
      else {   
        stmt = getStmt(conn, update[whichUpdate[i]]);
      }
      
      try {
        if (stmt!=null)
          if (rand.nextBoolean())
            updateTable(s, newCid[i], cid[i], cust_name[i], since[i], addr[i], tid, whichUpdate[i]);
          else
            updateTable(stmt, newCid[i], cid[i], cust_name[i], since[i], addr[i], tid, whichUpdate[i]);
      } catch (SQLException se) {
        if (se.getSQLState().equals("42502") && testSecurity) {
          Log.getLogWriter().info("Got the expected exception for authorization," +
             " continuing tests");
        } else
          SQLHelper.handleSQLException(se);
      }    
    }
  }  
}
 
Example #30
Source File: StatementsTest.java    From Komondor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test for PreparedStatement.executeLargeUpdate().
 * Validate update count returned and generated keys.
 * Case: explicitly requesting generated keys.
 */
public void testPrepStmtExecuteLargeUpdateExplicitGeneratedKeys() throws Exception {
    createTable("testExecuteLargeUpdate", "(id BIGINT AUTO_INCREMENT PRIMARY KEY, n INT)");

    this.pstmt = this.conn.prepareStatement("INSERT INTO testExecuteLargeUpdate (n) VALUES (?), (?), (?), (?), (?)", Statement.RETURN_GENERATED_KEYS);
    this.pstmt.setInt(1, 1);
    this.pstmt.setInt(2, 2);
    this.pstmt.setInt(3, 3);
    this.pstmt.setInt(4, 4);
    this.pstmt.setInt(5, 5);

    long count = this.pstmt.executeLargeUpdate();
    assertEquals(5, count);
    assertEquals(5, this.pstmt.getLargeUpdateCount());

    this.rs = this.pstmt.getGeneratedKeys();

    ResultSetMetaData rsmd = this.rs.getMetaData();
    assertEquals(1, rsmd.getColumnCount());
    assertEquals(JDBCType.BIGINT.getVendorTypeNumber().intValue(), rsmd.getColumnType(1));
    assertEquals(20, rsmd.getColumnDisplaySize(1));

    long generatedKey = 0;
    while (this.rs.next()) {
        assertEquals(++generatedKey, this.rs.getLong(1));
    }
    assertEquals(5, generatedKey);
    this.rs.close();
}