Example usage for java.sql SQLException getSQLState

List of usage examples for java.sql SQLException getSQLState

Introduction

In this page you can find the example usage for java.sql SQLException getSQLState.

Prototype

public String getSQLState() 

Source Link

Document

Retrieves the SQLState for this SQLException object.

Usage

From source file:io.cloudslang.content.database.utils.SQLUtils.java

/**
 * Some databases (Sybase) throw exceptions during a database dump. This function processes that exception, and if it is that type, builds up the output of the command
 *
 * @param sqlException The exception to analyze
 * @return The output of the dump command
 * @throws java.sql.SQLException If it was not a successful dump command's exception.
 *//*from  w ww. ja  va  2s  .  c  o  m*/
public static String processDumpException(SQLException sqlException) throws SQLException {
    final String sqlState = sqlException.getSQLState();

    if (sqlState != null && StringUtils.equalsIgnoreCase(sqlState, "s1000")) {
        SQLException f = sqlException;
        StringBuilder s = new StringBuilder();
        s.append(f.getMessage());
        while ((f = f.getNextException()) != null) {
            s.append("\n").append(f.getMessage());
        }
        String str = s.toString();
        if (StringUtils.containsIgnoreCase(str, "dump is complete"))
            return str;
    }
    throw sqlException;
}

From source file:org.seasar.dbflute.logic.DfDBFluteTaskUtil.java

public static void shutdownIfDerbyEmbedded(String driver) throws SQLException {
    if (!driver.startsWith("org.apache.derby.") || !driver.endsWith(".EmbeddedDriver")) {
        return;//from  w  ww  .ja  va2s  . c om
    }
    final String shutdownUrl = "jdbc:derby:;shutdown=true";
    Connection conn = null;
    try {
        _log.info("...Shutting down the connection to Derby");
        conn = DriverManager.getConnection(shutdownUrl);
    } catch (SQLException e) {
        if ("XJ015".equals(e.getSQLState())) {
            _log.info(" -> success: " + e.getMessage());
        } else {
            String msg = "Failed to shut down the connection to Derby:";
            msg = msg + " shutdownUrl=" + shutdownUrl;
            throw new DfJDBCException(msg, e);
        }
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:com.splicemachine.db.impl.ast.FindHashJoinColumns.java

private static ResultColumn resetColumnReference(ResultColumn resultColumn, ValueNode operand,
        BinaryRelationalOperatorNode brop, JoinNode joinNode, ResultSetNode resultSetNode)
        throws StandardException {

    try {/*from w w w .jav  a 2 s.c  om*/
        LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC();
        NodeFactory nodeFactory = lcc.getLanguageConnectionFactory().getNodeFactory();

        ColumnReference generatedRef = (ColumnReference) nodeFactory.getNode(C_NodeTypes.COLUMN_REFERENCE,
                resultColumn.getName(), null, ContextService.getService().getCurrentContextManager());
        VirtualColumnNode vnode = (VirtualColumnNode) nodeFactory.getNode(C_NodeTypes.VIRTUAL_COLUMN_NODE,
                resultSetNode, // source result set.
                resultColumn, resultSetNode.getResultColumns().size(),
                ContextService.getService().getCurrentContextManager());

        resultColumn = (ResultColumn) nodeFactory.getNode(C_NodeTypes.RESULT_COLUMN, resultColumn.getName(),
                vnode, ContextService.getService().getCurrentContextManager());
        resultColumn.markGenerated();
        resultColumn.setResultSetNumber(joinNode.getResultSetNumber());
        generatedRef.setSource(resultColumn);
        if (brop.getLeftOperand() == operand) {
            generatedRef
                    .setTableNumber(brop.getLeftOperand().getHashableJoinColumnReference().getTableNumber());
            brop.setLeftOperand(generatedRef);
        } else {
            generatedRef
                    .setTableNumber(brop.getRightOperand().getHashableJoinColumnReference().getTableNumber());
            brop.setRightOperand(generatedRef);
        }
        return resultColumn;
    } catch (SQLException e) {
        throw StandardException.newException(e.getSQLState());
    }
}

From source file:com.splicemachine.db.impl.ast.FindHashJoinColumns.java

private static ResultColumn addResultColumnToChild(ColumnReference cr, ValueNode operand,
        ResultSetNode resultSetNode, ResultColumnList rcl) throws StandardException {
    try {//from   www .  j  a  v a  2s  . co m
        LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC();
        NodeFactory nodeFactory = lcc.getLanguageConnectionFactory().getNodeFactory();

        // Add a result column and return virtual column Id
        ResultColumn rc = cr.getSource();
        assert rc.getExpression() instanceof VirtualColumnNode;
        VirtualColumnNode vn = (VirtualColumnNode) rc.getExpression();
        rc = vn.getSourceColumn();

        // construct a result column and add to result column list of child result set
        ColumnReference generatedRef = (ColumnReference) nodeFactory.getNode(C_NodeTypes.COLUMN_REFERENCE,
                rc.getName(), null, ContextService.getService().getCurrentContextManager());

        assert rc.getExpression() instanceof VirtualColumnNode;
        vn = (VirtualColumnNode) rc.getExpression();
        generatedRef.setSource(vn.getSourceColumn());
        generatedRef.setTableNumber(operand.getHashableJoinColumnReference().getTableNumber());
        operand.setHashableJoinColumnReference(generatedRef);

        ResultColumn resultColumn = (ResultColumn) nodeFactory.getNode(C_NodeTypes.RESULT_COLUMN,
                generatedRef.getColumnName(), operand, ContextService.getService().getCurrentContextManager());
        resultColumn.markGenerated();
        resultColumn.setResultSetNumber(resultSetNode.getResultSetNumber());
        resultColumn.setVirtualColumnId(rcl.size());
        rcl.addResultColumn(resultColumn);

        return resultColumn;
    } catch (SQLException e) {
        throw StandardException.newException(e.getSQLState());
    }
}

From source file:cai.sql.SQL.java

public static void error_msg(String msg, SQLException e, String stm) throws RuntimeException {
    String s = new String(
            "SQL: " + msg + ": " + e.getErrorCode() + "/" + e.getSQLState() + " " + e.getMessage());

    if (stm != null)
        s += "\nSQL: Statement `" + stm + "'";

    logger.error(s);//from  w ww  .  ja va2s  . c o  m

    if (JDBC_abort_on_error)
        throw new RuntimeException(s);
}

From source file:org.apache.airavata.registry.tool.DBMigrator.java

private static void executeSQL(String sql, Connection conn) throws Exception {
    if ("".equals(sql.trim())) {
        return;//from   w  ww  .j  a  v a 2 s  .  com
    }
    Statement statement = null;
    try {
        logger.debug("SQL : " + sql);

        boolean ret;
        int updateCount = 0, updateCountTotal = 0;
        statement = conn.createStatement();
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
            }
        } while (ret);

        logger.debug(sql + " : " + updateCountTotal + " rows affected");

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            logger.warn(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("X0Y32")) {
            logger.info("Table Already Exists", e);
        } else {
            throw new Exception("Error occurred while executing : " + sql, e);
        }
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                logger.error("Error occurred while closing result set.", e);
            }
        }
    }
}

From source file:cit360.sandbox.BackEndMenu.java

public final static void connect() {
    Connection conn = null;//from  ww w  .  j  a  v  a 2 s  .c  om
    try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost/cit361-sandbox?" + "user=root&password=");

        // Do something with the Connection

    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());

    }

    if (null != conn) {
        System.out.println("Connected to database!");
    } else {
        System.out.println("Failed to make connection!");
    }
    try {
        Statement stmt = conn.createStatement();
        String query = "select * from movies ;";
        //movies is the table name
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String name = rs.getObject(2).toString();
            String Start_Time = rs.getObject(3).toString();
            System.out.println(name + ": " + Start_Time);
            //movies table has name and price columns

        }
    } catch (SQLException e) {
        for (Throwable ex : e) {
            System.err.println("Error occurred " + ex);
        }
        System.out.println("Error in fetching data");
    }
}

From source file:com.oracle.tutorial.jdbc.JDBCTutorialUtilities.java

public static void alternatePrintSQLException(SQLException ex) {
    while (ex != null) {
        System.err.println("SQLState: " + ex.getSQLState());
        System.err.println("Error Code: " + ex.getErrorCode());
        System.err.println("Message: " + ex.getMessage());
        Throwable t = ex.getCause();
        while (t != null) {
            System.out.println("Cause: " + t);
            t = t.getCause();// www.jav  a  2 s .  com
        }
        ex = ex.getNextException();
    }
}

From source file:org.sonar.core.persistence.InMemoryDatabase.java

public static void stopDatabase() {
    try {/*from  w  w  w  .  j  av a2 s . c om*/
        if (datasource != null) {
            datasource.close();
            datasource = null;
        }
        DriverManager.getConnection("jdbc:derby:;shutdown=true");

    } catch (SQLException e) {
        // See http://db.apache.org/derby/docs/dev/getstart/rwwdactivity3.html
        // XJ015 indicates successful shutdown of Derby
        // 08006 successful shutdown of a single database
        if (!"XJ015".equals(e.getSQLState())) {
            throw new IllegalStateException("Fail to stop Derby", e);
        }
    }
}

From source file:org.openconcerto.sql.utils.SQLUtils.java

/**
 * Return the first chained exception with a non null SQL state.
 * //from   www .  j  a  va 2 s.c  o m
 * @param exn an exception.
 * @return the first SQLException with a non-<code>null</code>
 *         {@link SQLException#getSQLState()}, <code>null</code> if not found.
 */
static public final SQLException findWithSQLState(final Exception exn) {
    Throwable e = exn;
    while (e != null) {
        if (e instanceof SQLException) {
            final SQLException sqlExn = (SQLException) e;
            if (sqlExn.getSQLState() != null) {
                return sqlExn;
            }
        }
        e = e.getCause();
    }
    return null;
}