java.sql.PreparedStatement Java Examples
The following examples show how to use
java.sql.PreparedStatement.
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: TradePortfolioDMLStmt.java From gemfirexd-oss with Apache License 2.0 | 7 votes |
protected boolean deleteFromDerbyTable(Connection dConn, int whichDelete, int[]cid, int []sid, List<SQLException> exList){ PreparedStatement stmt = getStmt(dConn, delete[whichDelete]); if (stmt == null) return false; int tid = getMyTid(); int count = -1; try { for (int i=0; i<cid.length; i++) { verifyRowCount.put(tid+"_delete"+i, 0); count = deleteFromTable(stmt, cid[i], sid[i], tid, whichDelete); verifyRowCount.put(tid+"_delete"+i, new Integer(count)); } } catch (SQLException se) { if (!SQLHelper.checkDerbyException(dConn, se)) return false; else SQLHelper.handleDerbySQLException(se, exList); //handle the exception } return true; }
Example #2
Source File: H2CompareBigQueryTest.java From ignite with Apache License 2.0 | 6 votes |
/** * Insert {@link CustOrder} at h2 database. * * @param o CustOrder. */ private void insertInDb(CustOrder o) throws SQLException { try (PreparedStatement st = conn.prepareStatement( "insert into \"custord\".CustOrder (_key, _val, orderId, rootOrderId, date, alias, archSeq, origOrderId) " + "values(?, ?, ?, ?, ?, ?, ?, ?)")) { int i = 0; st.setObject(++i, o.orderId); st.setObject(++i, o); st.setObject(++i, o.orderId); st.setObject(++i, o.rootOrderId); st.setObject(++i, o.date); st.setObject(++i, o.alias); st.setObject(++i, o.archSeq); st.setObject(++i, o.origOrderId); st.executeUpdate(); } }
Example #3
Source File: QueryTest.java From phoenix with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testCoerceLongToDecimal2() throws Exception { String query = "SELECT entity_id FROM ATABLE WHERE organization_id=? AND x_integer <= x_decimal"; String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5 Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(ROW9, rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } }
Example #4
Source File: UserRegDAO.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
@Override public List<String> oldAccountsNotActivated(Date date) { List<String> usernames = new ArrayList<String>(); Timestamp timeBound = new Timestamp(date.getTime()); Connection conn = null; PreparedStatement stat = null; ResultSet res = null; String username = null; try { conn = this.getConnection(); stat = conn.prepareStatement(USERNAMES_FROM_OLD_ACCOUNT_REQUESTS); stat.setTimestamp(1, timeBound); res = stat.executeQuery(); while (res.next()) { username = res.getString("username"); usernames.add(username); } } catch (Throwable t) { _logger.error("error extracting oldAccountsNotActivated", t); throw new RuntimeException("error extracting oldAccountsNotActivated", t); } finally { closeDaoResources(res, stat, conn); } return usernames; }
Example #5
Source File: RdbTransactionLogStorage.java From sharding-jdbc-1.5.1 with Apache License 2.0 | 6 votes |
@Override public void add(final TransactionLog transactionLog) { String sql = "INSERT INTO `transaction_log` (`id`, `transaction_type`, `data_source`, `sql`, `parameters`, `creation_time`) VALUES (?, ?, ?, ?, ?, ?);"; try ( Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { preparedStatement.setString(1, transactionLog.getId()); preparedStatement.setString(2, SoftTransactionType.BestEffortsDelivery.name()); preparedStatement.setString(3, transactionLog.getDataSource()); preparedStatement.setString(4, transactionLog.getSql()); preparedStatement.setString(5, new Gson().toJson(transactionLog.getParameters())); preparedStatement.setLong(6, transactionLog.getCreationTime()); preparedStatement.executeUpdate(); } catch (final SQLException ex) { throw new TransactionLogStorageException(ex); } }
Example #6
Source File: DataCenterVnetDaoImpl.java From cosmic with Apache License 2.0 | 6 votes |
@Override @DB //In the List<string> argument each string is a vlan. not a vlanRange. public void add(final long dcId, final long physicalNetworkId, final List<String> vnets) { final String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id, physical_network_id) VALUES ( ?, ?, ?)"; final TransactionLegacy txn = TransactionLegacy.currentTxn(); try { txn.start(); final PreparedStatement stmt = txn.prepareAutoCloseStatement(insertVnet); for (int i = 0; i <= vnets.size() - 1; i++) { stmt.setString(1, vnets.get(i)); stmt.setLong(2, dcId); stmt.setLong(3, physicalNetworkId); stmt.addBatch(); } stmt.executeBatch(); txn.commit(); } catch (final SQLException e) { throw new CloudRuntimeException(e.getMessage()); } }
Example #7
Source File: CloudSqlDao.java From getting-started-java with Apache License 2.0 | 6 votes |
@Override public void updateBook(Book book) throws SQLException { final String updateBookString = "UPDATE books5 SET author = ?, createdBy = ?, createdById = ?, " + "description = ?, publishedDate = ?, title = ?, imageUrl = ? WHERE id = ?"; try (Connection conn = dataSource.getConnection(); PreparedStatement updateBookStmt = conn.prepareStatement(updateBookString)) { updateBookStmt.setString(1, book.getAuthor()); updateBookStmt.setString(2, book.getCreatedBy()); updateBookStmt.setString(3, book.getCreatedById()); updateBookStmt.setString(4, book.getDescription()); updateBookStmt.setString(5, book.getPublishedDate()); updateBookStmt.setString(6, book.getTitle()); updateBookStmt.setString(7, book.getImageUrl()); updateBookStmt.setLong(8, book.getId()); updateBookStmt.executeUpdate(); } }
Example #8
Source File: TradePortfolioDMLTxStmt.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
protected boolean updateToDerbyTableTidListTx(Connection conn, int cid, int sid, BigDecimal price, int qty, int whichUpdate, int tid) throws SQLException { PreparedStatement stmt = conn.prepareStatement(updateByTidList[whichUpdate]); int count = -1; Log.getLogWriter().info("update portfolio table in derby, myTid is " + getMyTid()); Log.getLogWriter().info("update statement is " + updateByTidList[whichUpdate]); try { count = updateToTableTidListTx(stmt, cid, sid, price, qty, whichUpdate, tid); } catch (SQLException se) { if (!SQLHelper.checkDerbyException(conn, se)) { //handles the deadlock of aborting Log.getLogWriter().info("detected the lock issue, will try it again"); return false; } else throw se; } Log.getLogWriter().info("derby updated " + count + " rows"); return true; }
Example #9
Source File: BasicJdbcDemo.java From HibernateDemos with The Unlicense | 6 votes |
private static void insertSkill(Skill skill) throws SQLException { Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement( "INSERT INTO skills VALUES(?, ?)" ); stmt.setInt( 1, skill.getId() ); stmt.setString( 2, skill.getName() ); stmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }
Example #10
Source File: ExtendedModeIT.java From spanner-jdbc with MIT License | 6 votes |
@Before public void createAndFillTestTable() throws SQLException { if (tableExists("test")) return; getConnection().createStatement().execute( "create table test (id int64 not null, name string(100) not null) primary key (id)"); getConnection().setAutoCommit(false); PreparedStatement ps = getConnection().prepareStatement("insert into test (id, name) values (?,?)"); for (int i = 0; i < NUMBER_OF_ROWS; i++) { ps.setLong(1, i); ps.setString(2, String.valueOf(i)); ps.addBatch(); } ps.executeBatch(); getConnection().commit(); }
Example #11
Source File: PercentileIT.java From phoenix with Apache License 2.0 | 6 votes |
@Test public void testPercentileDiscAsc() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(tenantId, null, getDefaultSplits(tenantId), null, ts); String query = "SELECT PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY A_INTEGER ASC) FROM aTable"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at // timestamp 2 Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); int percentile_disc = rs.getInt(1); assertEquals(9, percentile_disc); assertFalse(rs.next()); } finally { conn.close(); } }
Example #12
Source File: RDBMSDataHandler.java From micro-integrator with Apache License 2.0 | 6 votes |
@Override public List<ODataEntry> readTable(String tableName) throws ODataServiceFault { ResultSet resultSet = null; Connection connection = null; PreparedStatement statement = null; try { connection = initializeConnection(); String query = "select * from " + tableName; statement = connection.prepareStatement(query); resultSet = statement.executeQuery(); return createDataEntryCollectionFromRS(tableName, resultSet); } catch (SQLException e) { throw new ODataServiceFault(e, "Error occurred while reading entities from " + tableName + " table. :" + e.getMessage()); } finally { releaseResources(resultSet, statement); releaseConnection(connection); } }
Example #13
Source File: SideBarLogic.java From JspMyAdmin2 with GNU General Public License v2.0 | 6 votes |
/** * * @return * @throws Exception */ public List<String> getDatabaseList() throws Exception { List<String> databaseList = null; ApiConnection apiConnection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { apiConnection = getConnection(); statement = apiConnection.getStmtSelect("SHOW DATABASES"); resultSet = statement.executeQuery(); databaseList = new ArrayList<String>(); while (resultSet.next()) { databaseList.add(resultSet.getString(1)); } Collections.sort(databaseList); } finally { close(resultSet); close(statement); close(apiConnection); } return databaseList; }
Example #14
Source File: AbstractReturningDelegate.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public final Serializable performInsert( String insertSQL, SharedSessionContractImplementor session, Binder binder) { try { // prepare and execute the insert PreparedStatement insert = prepare( insertSQL, session ); try { binder.bindValues( insert ); return executeAndExtract( insert, session ); } finally { releaseStatement( insert, session ); } } catch (SQLException sqle) { throw session.getJdbcServices().getSqlExceptionHelper().convert( sqle, "could not insert: " + MessageHelper.infoString( persister ), insertSQL ); } }
Example #15
Source File: BasicSqlConnection.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 6 votes |
@Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { PreparedStatement statement; if (getJdbcSpecific().getAutoKeyType() == AutoGeneratedKeysType.SINGLE) { if (columnIndexes != null) { statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); }else{ logger.warn("Columns are null"); logger.info("Returning generated keys switched off"); statement = connection.prepareStatement(sql); } }else{ statement = connection.prepareStatement(sql, columnIndexes); } optimizeStatement(statement); return statement; }
Example #16
Source File: TradeSecuritiesDMLStmt.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
protected void insertToSecuritiesFulldataset (Connection conn, int sec_id, String symbol, BigDecimal price, String exchange, int tid){ //manually update fulldataset table for above entry. try{ Log.getLogWriter().info(" Trigger behaviour is not defined for putDML hence deleting the row from TRADE.SECURITIES_FULLDATASET with data SEC_ID:" + sec_id ); conn.createStatement().execute("DELETE FROM TRADE.SECURITIES_FULLDATASET WHERE sec_id = " + sec_id ); PreparedStatement preparedInsertStmt = conn.prepareStatement("insert into trade.SECURITIES_fulldataset values (?,?,?,?,?)"); preparedInsertStmt.setInt(1, sec_id); preparedInsertStmt.setString(2, symbol); preparedInsertStmt.setBigDecimal(3, price); preparedInsertStmt.setString(4, exchange); preparedInsertStmt.setInt(5, tid); Log.getLogWriter().info(" Trigger behaviour is not defined for putDML hence inserting the row into TRADE.SECURITIES_FULLDATASET with data SEC_ID:" + sec_id + ",SYMBOL" + symbol + ",EXCHANGE:" + exchange + ",PRICE:" + price + ".TID:" + tid ); preparedInsertStmt.executeUpdate(); } catch (SQLException se) { Log.getLogWriter().info("Error while updating TRADE.SECURITIES_FULLDATASET table. It may cause Data inconsistency " + se.getMessage() ); } }
Example #17
Source File: BatchUpdateUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
protected static void setStatementParameters(Object[] values, PreparedStatement ps, int[] columnTypes) throws SQLException { int colIndex = 0; for (Object value : values) { colIndex++; if (value instanceof SqlParameterValue) { SqlParameterValue paramValue = (SqlParameterValue) value; StatementCreatorUtils.setParameterValue(ps, colIndex, paramValue, paramValue.getValue()); } else { int colType; if (columnTypes == null || columnTypes.length < colIndex) { colType = SqlTypeValue.TYPE_UNKNOWN; } else { colType = columnTypes[colIndex - 1]; } StatementCreatorUtils.setParameterValue(ps, colIndex, colType, value); } } }
Example #18
Source File: MySQLDataHandler.java From ClaimChunk with MIT License | 6 votes |
@Override @Nullable public String getPlayerUsername(UUID player) { String sql = String.format("SELECT `%s` FROM `%s` WHERE `%s`=?", PLAYERS_IGN, PLAYERS_TABLE_NAME, PLAYERS_UUID); try (PreparedStatement statement = prep(claimChunk, connection, sql)) { statement.setString(1, player.toString()); try (ResultSet result = statement.executeQuery()) { if (result.next()) return result.getString(1); } } catch (Exception e) { Utils.err("Failed to retrieve player username: %s", e.getMessage()); e.printStackTrace(); } return null; }
Example #19
Source File: DatabaseConfigSource.java From tomee with Apache License 2.0 | 6 votes |
@Override public String getValue(final String propertyName) { try { final Connection connection = dataSource.getConnection(); final PreparedStatement query = connection.prepareStatement("SELECT VALUE FROM CONFIGURATIONS WHERE NAME = ?"); query.setString(1, propertyName); final ResultSet value = query.executeQuery(); if (value.next()) { return value.getString(1); } DbUtils.closeQuietly(value); DbUtils.closeQuietly(query); DbUtils.closeQuietly(connection); } catch (final SQLException e) { e.printStackTrace(); } return null; }
Example #20
Source File: Main.java From sharding-jdbc-1.5.1 with Apache License 2.0 | 6 votes |
private static void printHintSimpleSelect(final DataSource dataSource) throws SQLException { String sql = "SELECT i.* FROM t_order o JOIN t_order_item i ON o.order_id=i.order_id"; try ( HintManager hintManager = HintManager.getInstance(); Connection conn = dataSource.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { hintManager.addDatabaseShardingValue("t_order", "user_id", 10); hintManager.addTableShardingValue("t_order", "order_id", 1001); try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { System.out.println(rs.getInt(1)); System.out.println(rs.getInt(2)); System.out.println(rs.getInt(3)); } } } }
Example #21
Source File: ProductMetricsIT.java From phoenix with Apache License 2.0 | 6 votes |
@Test public void testFilterOnTrailingKeyColumn2() throws Exception { String tablename=generateUniqueName(); String tenantId = getOrganizationId(); String query = "SELECT organization_id, \"DATE\", feature FROM "+tablename+" WHERE substr(organization_id,1,3)=? AND \"DATE\" > to_date(?)"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { initTableValues(tablename, tenantId, getSplits(tenantId)); PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId.substring(0,3)); statement.setString(2, DS4); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(tenantId, rs.getString(1)); assertEquals(D5.getTime(), rs.getDate(2).getTime()); assertEquals(F3, rs.getString(3)); assertTrue(rs.next()); assertEquals(tenantId, rs.getString(1)); assertEquals(D6, rs.getDate(2)); assertEquals(F1, rs.getString(3)); assertFalse(rs.next()); } finally { conn.close(); } }
Example #22
Source File: CustPortfSoSubqueryStmt.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
private ResultSet getUniqQuery5(Connection conn, int whichQuery, int tid, boolean[] success) { PreparedStatement stmt; ResultSet rs = null; success[0] = true; try { Log.getLogWriter().info("which query is -- " + uniqSelect[whichQuery]); stmt = conn.prepareStatement(uniqSelect[whichQuery]); Log.getLogWriter().info("data used in query -- tid: "+ tid); stmt.setInt(1, tid); stmt.setInt(2, tid); rs = stmt.executeQuery(); } catch (SQLException se) { SQLHelper.printSQLException(se); if (!isTicket42422Fixed && se.getSQLState().equalsIgnoreCase("0A000")) { Log.getLogWriter().info("get unsupported exception for union query, continue testing"); success[0] = true; return null; //only suitable for cases when derby DB is available. } if (!SQLHelper.checkDerbyException(conn, se)) success[0] = false; //handle lock could not acquire or deadlock else if (!SQLHelper.checkGFXDException(conn, se)) success[0] = false; //hand X0Z01 and #41471 else SQLHelper.handleSQLException(se); } return rs; }
Example #23
Source File: VariableLengthPKIT.java From phoenix with Apache License 2.0 | 6 votes |
@Test public void testNonfirstColumnGroupBy() throws Exception { String pTSDBTableName = generateUniqueName(); String query = "SELECT HOST FROM "+pTSDBTableName+" WHERE INST='abc' GROUP BY HOST"; String url = getUrl(); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initPTSDBTableValues(null, pTSDBTableName); PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals("abc-def-ghi", rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } }
Example #24
Source File: ProductDAO.java From maven-framework-project with MIT License | 5 votes |
public boolean remove(Product product) { Connection c = null; try { c = this.dataSource.getConnection(); PreparedStatement ps = c.prepareStatement("DELETE FROM product WHERE id=?"); ps.setInt(1, product.getProductId()); int count = ps.executeUpdate(); return count == 1; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example #25
Source File: GemFireXDDataExtractorDUnit.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private void insertData(String tableName, int startIndex, int endIndex) throws SQLException{ Connection connection = TestUtil.getConnection(); PreparedStatement ps = connection.prepareStatement("INSERT INTO " + tableName + "(bigIntegerField, blobField, charField," + "charForBitData, clobField, dateField, decimalField, doubleField, floatField, longVarcharForBitDataField, numericField," + "realField, smallIntField, timeField, timestampField, varcharField, varcharForBitData, xmlField) values( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, xmlparse(document cast (? as clob) PRESERVE WHITESPACE))"); for (int i = startIndex; i < endIndex; i++) { int lessThan10 = i % 10; ps.setLong(1, i); //BIG INT ps.setBlob(2,new ByteArrayInputStream(new byte[]{(byte)i,(byte)i,(byte)i,(byte)i})); ps.setString(3, ""+lessThan10); ps.setBytes(4, ("" + lessThan10).getBytes()); ps.setClob(5, new StringReader("SOME CLOB " + i)); ps.setDate(6, new Date(System.currentTimeMillis())); ps.setBigDecimal(7, new BigDecimal(lessThan10 + .8)); ps.setDouble(8, i + .88); ps.setFloat(9, i + .9f); ps.setBytes(10, ("A" + lessThan10).getBytes()); ps.setBigDecimal(11, new BigDecimal(i)); ps.setFloat(12, lessThan10 * 1111); ps.setShort(13, (short)i); ps.setTime(14, new Time(System.currentTimeMillis())); ps.setTimestamp(15, new Timestamp(System.currentTimeMillis())); ps.setString(16, "HI" + lessThan10); ps.setBytes(17, ("" + lessThan10).getBytes()); ps.setClob(18, new StringReader("<xml><sometag>SOME XML CLOB " + i + "</sometag></xml>")); ps.execute(); } }
Example #26
Source File: JDBC4CallableStatementWrapper.java From Komondor with GNU General Public License v3.0 | 5 votes |
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { try { if (this.wrappedStmt != null) { ((PreparedStatement) this.wrappedStmt).setCharacterStream(parameterIndex, reader); } else { throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor); } } catch (SQLException sqlEx) { checkAndFireConnectionError(sqlEx); } }
Example #27
Source File: PreparedStatementAdapterTest.java From shardingsphere with Apache License 2.0 | 5 votes |
@Test public void assertSetTime() throws SQLException { for (PreparedStatement each : preparedStatements) { Time now = new Time(0L); each.setTime(1, now); each.setTime(2, now, Calendar.getInstance()); assertParameter(each, 1, now); assertParameter(each, 2, now); } }
Example #28
Source File: AggregateQueryIT.java From phoenix with Apache License 2.0 | 5 votes |
@Test public void testCountIsNull() throws Exception { String query = "SELECT count(1) FROM " + tableName + " WHERE X_DECIMAL is null"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue (rs.next()); assertEquals(6, rs.getLong(1)); assertFalse(rs.next()); } finally { conn.close(); } }
Example #29
Source File: TradeNetworthDMLStmtJson.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
protected void deleteFromGFETable(Connection gConn, int whichDelete, int cid){ PreparedStatement stmt = getStmt(gConn, delete[whichDelete]); if (SQLTest.testSecurity && stmt == null) { if (SQLSecurityTest.prepareStmtException.get() != null) { SQLSecurityTest.prepareStmtException.set(null); return; } else ; //need to find out why stmt is not obtained } //work around #43244 if (setCriticalHeap && stmt == null) { return; //prepare stmt may fail due to XCL54 now } if (stmt == null && alterTableDropColumn) { Log.getLogWriter().info("prepare stmt failed due to missing column"); return; //prepare stmt may fail due to alter table now } int tid = getMyTid(); try { deleteFromTable(stmt, cid, tid, whichDelete); } catch (SQLException se) { if ((se.getSQLState().equals("42500") || se.getSQLState().equals("42502")) && testSecurity) { Log.getLogWriter().info("Got the expected exception for authorization," + " continuing tests"); } else if (alterTableDropColumn && se.getSQLState().equals("42X14")) { Log.getLogWriter().info("Got expected column not found exception in delete, continuing test"); } else SQLHelper.handleSQLException(se); //handle the exception } }
Example #30
Source File: AlterTableTest.java From phoenix with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDisallowAddingNotNullableColumnNotPartOfPkForExistingTable() throws Exception { Properties props = new Properties(TEST_PROPERTIES); Connection conn = null; PreparedStatement stmt = null; try { conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(false); try { String ddl = "CREATE TABLE test_table " + " (a_string varchar not null, col1 integer, cf1.col2 integer" + " CONSTRAINT pk PRIMARY KEY (a_string))\n"; stmt = conn.prepareStatement(ddl); stmt.execute(); } finally { closeStatement(stmt); } try { stmt = conn.prepareStatement("ALTER TABLE test_table ADD b_string VARCHAR NOT NULL"); stmt.execute(); fail("Should have failed since altering a table by adding a non-nullable column is not allowed."); } catch (SQLException e) { assertEquals(SQLExceptionCode.CANNOT_ADD_NOT_NULLABLE_COLUMN.getErrorCode(), e.getErrorCode()); } finally { closeStatement(stmt); } } finally { closeConnection(conn); } }