Java Code Examples for java.sql.SQLException#getMessage()

The following examples show how to use java.sql.SQLException#getMessage() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hadoop   File: DBRecordReader.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void close() throws IOException {
  try {
    if (null != results) {
      results.close();
    }
    if (null != statement) {
      statement.close();
    }
    if (null != connection) {
      connection.commit();
      connection.close();
    }
  } catch (SQLException e) {
    throw new IOException(e.getMessage());
  }
}
 
Example 2
Source Project: conductor   File: MySQLBaseDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initialize a new transactional {@link Connection} from {@link #dataSource} and pass it to {@literal function}.
 * <p>
 * Successful executions of {@literal function} will result in a commit and return of
 * {@link TransactionalFunction#apply(Connection)}.
 * <p>
 * If any {@link Throwable} thrown from {@code TransactionalFunction#apply(Connection)} will result in a rollback
 * of the transaction
 * and will be wrapped in an {@link ApplicationException} if it is not already one.
 * <p>
 * Generally this is used to wrap multiple {@link #execute(Connection, String, ExecuteFunction)} or
 * {@link #query(Connection, String, QueryFunction)} invocations that produce some expected return value.
 *
 * @param function The function to apply with a new transactional {@link Connection}
 * @param <R>      The return type.
 * @return The result of {@code TransactionalFunction#apply(Connection)}
 * @throws ApplicationException If any errors occur.
 */
private <R> R getWithTransaction(final TransactionalFunction<R> function){
    final Instant start = Instant.now();
    LazyToString callingMethod = getCallingMethod();
    logger.trace("{} : starting transaction", callingMethod);

    try(Connection tx = dataSource.getConnection()) {
        boolean previousAutoCommitMode = tx.getAutoCommit();
        tx.setAutoCommit(false);
        try {
            R result = function.apply(tx);
            tx.commit();
            return result;
        } catch (Throwable th) {
            tx.rollback();
            throw new ApplicationException(BACKEND_ERROR, th.getMessage(), th);
        } finally {
            tx.setAutoCommit(previousAutoCommitMode);
        }
    } catch (SQLException ex) {
        throw new ApplicationException(BACKEND_ERROR, ex.getMessage(), ex);
    } finally {
        logger.trace("{} : took {}ms", callingMethod, Duration.between(start, Instant.now()).toMillis());
    }
}
 
Example 3
Source Project: micro-integrator   File: ClaimDAO.java    License: Apache License 2.0 6 votes vote down vote up
protected int addDialect(Connection dbConnection, String uri) throws UserStoreException {
    int dialectId = -1;
    PreparedStatement prepStmt = null;
    try {
        prepStmt = dbConnection.prepareStatement(ClaimDBConstants.ADD_DIALECT_SQL);
        prepStmt.setString(1, uri);
        prepStmt.setInt(2, tenantId);
        prepStmt.executeUpdate();
        prepStmt.close();
        dialectId = getDialect(dbConnection, uri);
    } catch (SQLException e) {
        log.error("Database Error - " + e.getMessage(), e);
        throw new UserStoreException("Database Error - " + e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(null, prepStmt);
    }
    return dialectId;
}
 
Example 4
Source Project: mdw   File: TaskServicesImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setElapsedTime(String ownerType, Long instanceId, Long elapsedTime) throws ServiceException {
    try {
        getTaskDAO().setElapsedTime(ownerType, instanceId, elapsedTime);
    }
    catch (SQLException ex) {
        throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
    }
}
 
Example 5
/**
 *
 *
 * @throws SQLException, IOException, InterruptedException
 */
public void testStartSlaveConnect_Illegal()
throws SQLException, IOException, InterruptedException
{
    System.out.println("**** TestPreStartedSlaveServer.testStartSlaveConnect_Illegal() "+
            getTestConfiguration().getJDBCClient().getJDBCDriverName());
    
    Connection conn = null;
    String db = slaveDatabasePath +"/"+ReplicationRun.slaveDbSubPath +"/"+ replicatedDb;
    String connectionURL = "jdbc:derby:"  
            + "//" + slaveServerHost + ":" + slaveServerPort + "/"
            + db
            + ";startSlave=true"
            + ";slavehost=" + slaveServerHost 
            + ";slaveport=" + slaveServerPort;
    System.out.println(connectionURL);
    try
    {
        conn = DriverManager.getConnection(connectionURL);
    }
    catch (SQLException se)
    {
        int ec = se.getErrorCode();
        String ss = se.getSQLState();
        String msg = ec + " " + ss + " " + se.getMessage();
        System.out.println("testStartSlaveConnect_Illegal: " + msg);
        // 40000 08001
        assertSQLState("Unexpected SQLException: " + msg, "08001", se);
        return;
    }
    assertTrue("Expected SQLException: '40000 08001 " + db + "'",false);
}
 
Example 6
@Override
public boolean first() throws IOException {
    if(closed) {
        throw new IOException("Cursor is closed");
    }
    try {
        return resultSet.first();
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new IOException(ex.getMessage());
    }
}
 
Example 7
Source Project: cloudstack   File: Upgrade410to420.java    License: Apache License 2.0 5 votes vote down vote up
private void migrateTemplateSwiftRef(Connection conn, Map<Long, Long> swiftStoreMap) {
    s_logger.debug("Updating template_store_ref table from template_swift_ref table");
    try (
            PreparedStatement tmplStoreInsert =
                conn.prepareStatement("INSERT INTO `cloud`.`template_store_ref` (store_id,  template_id, created, download_pct, size, physical_size, download_state, local_path, install_path, update_count, ref_cnt, store_role, state) values(?, ?, ?, 100, ?, ?, 'DOWNLOADED', '?', '?', 0, 0, 'Image', 'Ready')");
            PreparedStatement s3Query = conn.prepareStatement("select swift_id, template_id, created, path, size, physical_size from `cloud`.`template_swift_ref`");
            ResultSet rs = s3Query.executeQuery();
        ) {
        while (rs.next()) {
            Long swift_id = rs.getLong("swift_id");
            Long tmpl_id = rs.getLong("template_id");
            Date created = rs.getDate("created");
            String path = rs.getString("path");
            Long size = rs.getObject("size") != null ? rs.getLong("size") : null;
            Long psize = rs.getObject("physical_size") != null ? rs.getLong("physical_size") : null;

            tmplStoreInsert.setLong(1, swiftStoreMap.get(swift_id));
            tmplStoreInsert.setLong(2, tmpl_id);
            tmplStoreInsert.setDate(3, created);
            if (size != null) {
                tmplStoreInsert.setLong(4, size);
            } else {
                tmplStoreInsert.setNull(4, Types.BIGINT);
            }
            if (psize != null) {
                tmplStoreInsert.setLong(5, psize);
            } else {
                tmplStoreInsert.setNull(5, Types.BIGINT);
            }
            tmplStoreInsert.setString(6, path);
            tmplStoreInsert.setString(7, path);
            tmplStoreInsert.executeUpdate();
        }
    } catch (SQLException e) {
        String msg = "Unable to migrate template_swift_ref." + e.getMessage();
        s_logger.error(msg);
        throw new CloudRuntimeException(msg, e);
    }
    s_logger.debug("Completed migrating template_swift_ref table.");
}
 
Example 8
@Override
public ListTablesResponse doListTables(final BlockAllocator blockAllocator, final ListTablesRequest listTablesRequest)
{
    try (Connection connection = jdbcConnectionFactory.getConnection(getCredentialProvider())) {
        LOGGER.info("{}: List table names for Catalog {}, Table {}", listTablesRequest.getQueryId(), listTablesRequest.getCatalogName(), listTablesRequest.getSchemaName());
        return new ListTablesResponse(listTablesRequest.getCatalogName(), listTables(connection, listTablesRequest.getSchemaName()));
    }
    catch (SQLException sqlException) {
        throw new RuntimeException(sqlException.getErrorCode() + ": " + sqlException.getMessage());
    }
}
 
Example 9
private void sendUpdates() {
  synchronized (sendUpdatesMutex) {
    try {
      LOG.debug("Sending status updates");
      stream.forceUpdateStatus();
    } catch (SQLException e) {
      LOG.error("Error forcing update status: {}", e.getMessage());
      throw new StageException(JDBC_00, " forceUpdateStatus failed :" + e.getMessage(), e);
    }
  }
}
 
Example 10
Source Project: gemfirexd-oss   File: testListAggTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testDuplicateValueRemoval() {
	try {
		System.out.println("-----\ntestDuplicateValueRemoval\n------");
		String result = setParameters("ID", "SECONDID", "XML_DOC_1", "",
				",");
		assertTrue(result.equals("OK"));

		long startTime = new Date().getTime();
		cs.execute();
		long endTime = new Date().getTime();
		long elapsed = endTime - startTime;
		assertTrue(elapsed < 50);

		checkResultsMeta(4, 2);
		String colValue = (String) getCellValue(0, 1);

		// 2 - 1,1,3
		// 3 - 3,3
		// 4 - 4
		// 5 - 5
		assertTrue("Duplicate value:" + colValue, colValue.equals("1,3"));

	} catch (SQLException e) {
		String err = e.getMessage();
		fail("Unexpected exception:" + err);

	}
}
 
Example 11
Source Project: gemfirexd-oss   File: testListAggTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testSortDecimalDESCColumns() {
	try {
		String result = setParameters("SECONDID DESC", "THIRDID",
				"XML_DOC_1", "", ",");
		assertTrue(result.equals("OK"));
		long startTime = new Date().getTime();
		cs.execute();
		long endTime = new Date().getTime();
		long elapsed = endTime - startTime;
		assertTrue("Elapsed time:" + elapsed, elapsed < 500);
		System.out.println("Two columns results:");
		checkResultsMeta(4, 2);
		String colValue = (String) getCellValue(0, 0);
		assertTrue("Value=" + colValue, colValue.equals("5"));
		colValue = (String) getCellValue(0, 1);
		assertTrue("Value=" + colValue, colValue.equals("3"));

		colValue = (String) getCellValue(1, 0);
		assertTrue("Value=" + colValue, colValue.equals("4"));
		colValue = (String) getCellValue(1, 1);
		assertTrue("Value=" + colValue, colValue.equals("3"));

		colValue = (String) getCellValue(2, 0);
		assertTrue("Value=" + colValue, colValue.equals("3"));
		colValue = (String) getCellValue(2, 1);
		assertTrue("Value=" + colValue, colValue.equals("3,4"));
		
		colValue = (String) getCellValue(3, 0);
		assertTrue("Value=" + colValue, colValue.equals("1"));
		colValue = (String) getCellValue(3, 1);
		assertTrue("Value=" + colValue, colValue.equals("3,9"));
		
		

	} catch (SQLException e) {
		String err = e.getMessage();
		fail("Unexpected exception:" + err);
	}
}
 
Example 12
@Override
public void close() throws IOException {
    try {
        conn.close();
        conn = null;
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new IOException(ex.getMessage());
    }
}
 
Example 13
public void rollBackConnection() {
	try {
		this.connection.rollback();
	} catch (SQLException e) {
		e.printStackTrace();
		throw new FixFlowDbException(e.getMessage(), e);
	}
}
 
Example 14
Source Project: selenium   File: JdbcBackedSessionMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void remove(SessionId id) {
  Require.nonNull("Session ID", id);

  try (PreparedStatement statement = getDeleteSqlForSession(id)) {
    statement.executeUpdate();
  } catch (SQLException e) {
    throw new JdbcException(e.getMessage());
  }
}
 
Example 15
Source Project: micro-integrator   File: ClaimDAO.java    License: Apache License 2.0 5 votes vote down vote up
public void addClaimMapping(ClaimMapping claim) throws UserStoreException {
    Connection dbConnection = null;
    try {
        dbConnection = dataSource.getConnection();
        dbConnection.setAutoCommit(false);
        this.addClaimMapping(dbConnection, claim);
        dbConnection.commit();
    } catch (SQLException e) {
        log.error("Database Error - " + e.getMessage(), e);
        throw new UserStoreException("Database Error - " + e.getMessage(), e);
    } finally {
        DatabaseUtil.closeConnection(dbConnection);
    }
}
 
Example 16
Source Project: gemfirexd-oss   File: UseCase2TestCases.java    License: Apache License 2.0 5 votes vote down vote up
public void testUseCase2TestLastListAggFieldNoSummary() {
	try {
		String result = setParameters(
				"IDX_COL1 ASC, IDX_COL2 DESC,IDX_COL3 ASC, IDX_COL4 ASC, IDX_COL5 ASC,XML_DOC_ID_NBR ASC",
				"XML_DOC_ID_NBR",
				"XML_IDX_1_1",
				"IDX_COL1 like '9500%'and IDX_COL2 like'809%' and IDX_COL3='COLORADOSPRINGS'and IDX_COL4='CO' and IDX_COL5='US'",
				",");
		assertTrue("Set parameters = " + result, result.equals("OK"));
		long startTime = new Date().getTime();
		cs.execute();
		System.out.println("Elapsed time = "
				+ (new Date().getTime() - startTime));
		collectResults(cs);

		String[] expectedResults = {
				"9500ELMSTREET|80918|COLORADOSPRINGS|CO|US|1347036371777100019",
				"9500LUCKYSTREET|80911|COLORADOSPRINGS|CO|US|1347036371778100010",
				"9500OLDROAD|80917|COLORADOSPRINGS|CO|US|1347036371777100013",
				"9500REDROAD|80908|COLORADOSPRINGS|CO|US|1347036371777100014",
				"9500ROCKYROAD|80918|COLORADOSPRINGS|CO|US|1347036371777100011",
				"9500ROCKYSTREET|80919|COLORADOSPRINGS|CO|US|1347036371777100012",
				"9500ROUGHROAD|80914|COLORADOSPRINGS|CO|US|1347036371777100015",
				"9500SOMESTREET|80907|COLORADOSPRINGS|CO|US|1347036371777100016",
				"9500SOMESTREET|80903|COLORADOSPRINGS|CO|US|1347036371777100018",
				"9500SOMESTREET|80901|COLORADOSPRINGS|CO|US|1347036371777100017"
				
				 };

		String resultsMatch = compareResultsToMaster(expectedResults);
		assertTrue("Results did not match expected:" + resultsMatch,
				resultsMatch == null);
	} catch (SQLException e) {
		String err = e.getMessage();
		// e.printStackTrace();
		fail("Unexpected exeception:" + err);
	}
	
	
}
 
Example 17
Source Project: cloudstack   File: Upgrade4930to41000.java    License: Apache License 2.0 5 votes vote down vote up
private void updateSourceCidrs(Connection conn){
    //with ipset the value for source cidr 0.0.0.0/0 can't be added in ipset. So changing it to network cidr.
    try(PreparedStatement pstmt = conn.prepareStatement("UPDATE `cloud`.`firewall_rules_cidrs` AS s, (SELECT IFNULL(networks.network_cidr,networks.cidr) cidr," +
            "`firewall_rules_cidrs`.`id`, `firewall_rules`.`traffic_type` "+
            "FROM `cloud`.`networks`, `cloud`.`firewall_rules`,`cloud`.`firewall_rules_cidrs` WHERE `cloud`.`networks`.`id`=`cloud`.`firewall_rules`.`network_id` " +
            "AND `cloud`.`firewall_rules`.`id` = `cloud`.`firewall_rules_cidrs`.`firewall_rule_id`) AS p " +
            "SET `s`.`source_cidr` = `p`.`cidr` WHERE `s`.`source_cidr`=\"0.0.0.0/0\" AND `s`.`id`=`p`.`id` AND `p`.`traffic_type`=\"Egress\" ;")){
        pstmt.execute();
    }catch (SQLException e) {
        throw new CloudRuntimeException("updateSourceCidrs:Exception:" + e.getMessage(), e);
    }
}
 
Example 18
Source Project: SimpleFlatMapper   File: SelectQueryMapper.java    License: MIT License 5 votes vote down vote up
public <SET extends TableLike & ResultQuery> AutoCloseableEnumerable<T> enumerate(SET source)
        throws MappingException {
    SetRowMapper<ResultSet, ResultSet, T, SQLException> mapper = getMapper(source);
    try {
        final ResultSet rs = source.fetchResultSet();
        final Enumerable<T> enumerable = new ExceptionTranslatorEnumerable<T>(mapper.enumerate(rs));
        return new AutoCloseableEnumerable<T>(enumerable, closer(rs));
    } catch (SQLException e) {
        throw new DataAccessException(e.getMessage(), e);
    }
}
 
Example 19
Source Project: micro-integrator   File: DSGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void makeService(String dbName, String[] tableNames,
                            DatabaseMetaData metaData, DataService dataService, String schema)
		throws SQLException {
	for (String tableName : tableNames) {
                       String tablePrimaryKey = "";
                       try {
                               tablePrimaryKey = this.getPrimaryKey(metaData, dbName,
                                       schema, tableName);
                       } catch (SQLException e) {
                               throw new SQLException("Cannot create the service : " + e.getMessage());
                       }
		this.addOperations(dataService, schema, metaData, dbName,
				tableName, tablePrimaryKey);
	}
}
 
Example 20
/**
 * JDBC 2.0
 * <p/>
 * Submit a batch of commands to the database for execution.
 * This method is optional.
 * <p/>
 * Moving jdbc2.0 batch related code in this class because
 * callableStatement in jdbc 20 needs this code too and it doesn't derive
 * from prepared statement in jdbc 20 in our implementation.
 * BatchUpdateException is the only new class from jdbc 20 which is being
 * referenced here and in order to avoid any jdk11x problems, using
 * reflection code to make an instance of that class.
 *
 * @return an array of update counts containing one element for each
 * command in the batch.  The array is ordered according
 * to the order in which commands were inserted into the batch
 * @throws SQLException if a database-access error occurs, or the
 *                      driver does not support batch statements
 */
@Override
public int[] executeBatch() throws SQLException {
    checkExecStatus();
    synchronized (getConnectionSynchronization()) {
        setupContextStack();
        int i = 0;
        // As per the jdbc 2.0 specs, close the statement object's current resultset
        // if one is open.
        // Are there results?
        // outside of the lower try/finally since results will
        // setup and restore themselves.
        clearResultSets();

        Vector stmts = batchStatements;
        batchStatements = null;
        int size;
        if (stmts == null)
            size = 0;
        else
            size = stmts.size();

        int[] returnUpdateCountForBatch = new int[size];

        SQLException sqle;
        try {
            for (; i < size; i++) {
                // If we saw an interrupt, stop execution of batch now.
                // throwIf will likely only throw after at least one stm
                // has been executed, since first time around we probably
                // didn't do anything to notice interrupts yet.
                InterruptStatus.throwIf(lcc);
                if (executeBatchElement(stmts.get(i)))
                    throw newSQLException(SQLState.RESULTSET_RETURN_NOT_ALLOWED);
                returnUpdateCountForBatch[i] = getUpdateCount();
            }

            InterruptStatus.restoreIntrFlagIfSeen(lcc);
            return returnUpdateCountForBatch;
        } catch (StandardException se) {

            sqle = handleException(se);
        } catch (SQLException sqle2) {
            sqle = sqle2;
        } finally {
            restoreContextStack();
        }

        int successfulUpdateCount[] = new int[i];
        System.arraycopy(returnUpdateCountForBatch, 0, successfulUpdateCount, 0, i);

        SQLException batch =
                new java.sql.BatchUpdateException(sqle.getMessage(), sqle.getSQLState(),
                        sqle.getErrorCode(), successfulUpdateCount, sqle);

        batch.setNextException(sqle);
        throw batch;
    }
}