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:com.nilostep.xlsql.database.xlInstance.java

/**
 * get java.sql.Connection to engine// ww  w  .  ja v  a 2  s .com
 * 
 * @return Connection
 */
public Connection connect() {
    Connection ret = null;

    try {
        String classname = this.getDriver();
        logger.info("=> loading driver: " + classname);

        Driver d = (Driver) Class.forName(classname).newInstance();
        logger.info("OK. " + classname + " loaded.");
        logger.info("=> registering driver: " + classname);
        DriverManager.registerDriver(new xlEngineDriver(d));
        logger.info("OK. ");

        String url = getUrl();
        String user = getUser();
        String password = getPassword();
        logger.info("=> connecting to: " + user + "/" + password + "@" + url);
        ret = DriverManager.getConnection(url, user, password);
    } catch (ClassNotFoundException nfe) {
        logger.warning("Driver not found. Classpath set?");
    } catch (InstantiationException ie) {
        logger.warning("Error while instantiating driver class. ..?");
    } catch (IllegalAccessException iae) {
        logger.warning("Illegal access. Have sources been modified?");
    } catch (SQLException sqe) {
        logger.warning("java.sql package reports: '" + sqe.getMessage() + ":" + sqe.getSQLState() + "' ..?");
    }

    return ret;
}

From source file:fedora.server.storage.ConnectionPool.java

private void shutdownEmbeddedDB(String username, String password) {
    LOG.info("Shutting down embedded derby database.");
    try {/* w w w  .ja va2 s.c om*/
        DriverManager.getConnection("jdbc:derby:;shutdown=true", username, password);
    } catch (SQLException e) {
        // Shutdown throws the XJ015 exception to confirm success.
        if (!e.getSQLState().equals("XJ015")) {
            LOG.error("Embedded Derby DB did not shut down normally.");
        }
    }
}

From source file:JDBCPool.dbcp.demo.sourcecode.PoolableConnection.java

/**
 * Checks the SQLState of the input exception and any nested SQLExceptions it wraps.
 * <p>/*from   w  ww  .  j  a  va2  s  . co m*/
 * If {@link #getDisconnectSqlCodes() disconnectSQLCodes} has been set, sql states
 * are compared to those in the configured list of fatal exception codes.  If this
 * property is not set, codes are compared against the default codes in
 * #{@link Utils.DISCONNECTION_SQL_CODES} and in this case anything starting with
 * #{link Utils.DISCONNECTION_SQL_CODE_PREFIX} is considered a disconnection.</p>
 *
 * @param e SQLException to be examined
 * @return true if the exception signals a disconnection
 */
private boolean isDisconnectionSqlException(SQLException e) {
    boolean fatalException = false;
    String sqlState = e.getSQLState();
    if (sqlState != null) {
        fatalException = _disconnectionSqlCodes == null
                ? sqlState.startsWith(Utils.DISCONNECTION_SQL_CODE_PREFIX)
                        || Utils.DISCONNECTION_SQL_CODES.contains(sqlState)
                : _disconnectionSqlCodes.contains(sqlState);
        if (!fatalException) {
            if (e.getNextException() != null) {
                fatalException = isDisconnectionSqlException(e.getNextException());
            }
        }
    }
    return fatalException;
}

From source file:org.seasar.dbflute.exception.handler.SQLExceptionHandler.java

protected String extractSQLState(SQLException e) {
    String sqlState = e.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }/* w w w .  j a va 2  s.c  om*/

    // Next
    SQLException nextEx = e.getNextException();
    if (nextEx == null) {
        return null;
    }
    sqlState = nextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // Next Next
    SQLException nextNextEx = nextEx.getNextException();
    if (nextNextEx == null) {
        return null;
    }
    sqlState = nextNextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // Next Next Next
    SQLException nextNextNextEx = nextNextEx.getNextException();
    if (nextNextNextEx == null) {
        return null;
    }
    sqlState = nextNextNextEx.getSQLState();
    if (sqlState != null) {
        return sqlState;
    }

    // It doesn't use recursive call by design because JDBC is unpredictable fellow.
    return null;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.composite.MessageComposite.java

/**
 * SQLException to pretty message/*w  ww . j  a  v  a  2 s . co m*/
 * 
 * @param sqlException
 * @param tadpoleMessageDAO
 * @return
 */
private String sqlExceptionToSearchMsg(SQLException sqlException, TadpoleMessageDAO tadpoleMessageDAO) {
    String strNewMessage = "";
    try {
        StringBuffer sbMsg = new StringBuffer();
        sbMsg.append(String.format(" %s %s", sqlException.getSQLState(), sqlException.getErrorCode()));
        //         sbMsg.append(String.format(" %s", sqlException.getMessage()));

        strNewMessage = sbMsg.toString();
    } catch (Exception e) {
        logger.error("SQLException to striing", e); //$NON-NLS-1$
        strNewMessage = tadpoleMessageDAO.getStrMessage();
    }

    return strNewMessage;
}

From source file:org.wso2.carbon.identity.application.common.persistence.IdentityApplicationDBInitializer.java

private void executeSQL(String sql) throws SQLException {

    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;/*from  w  ww  . j ava 2 s  .  co  m*/
    }
    Connection conn = null;
    ResultSet resultSet = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("SQL : " + sql);
        }
        boolean ret;
        int updateCount, updateCountTotal = 0;
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
                resultSet = statement.getResultSet();
            }
        } while (ret);
        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        conn = dataSource.getConnection();
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("42710")) {
            // eliminating the table already exception for the derby and DB2 database types
            if (log.isDebugEnabled()) {
                log.info(
                        "Identity Application Management database already exists. Not creating a new database");
            }
        } else {
            throw e;
        }
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:RSAccounts.java

public void connectToDB() {
    try {/*from   www.j  av a2s .  c o  m*/
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
        statement = connection.createStatement();

    } catch (SQLException connectException) {
        System.out.println(connectException.getMessage());
        System.out.println(connectException.getSQLState());
        System.out.println(connectException.getErrorCode());
        System.exit(1);
    }
}

From source file:org.sakaiproject.sitestats.impl.DBHelper.java

public void preloadDefaultReports() {
    HibernateCallback hcb = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Connection c = null;// w  ww.  ja  v a  2 s .  c om
            InputStreamReader isr = null;
            BufferedReader br = null;
            try {
                ClassPathResource defaultReports = new ClassPathResource(dbVendor + "/default_reports.sql");
                LOG.info("init(): - preloading sitestats default reports");
                isr = new InputStreamReader(defaultReports.getInputStream());
                br = new BufferedReader(isr);

                c = session.connection();
                String sqlLine = null;
                while ((sqlLine = br.readLine()) != null) {
                    sqlLine = sqlLine.trim();
                    if (!sqlLine.equals("") && !sqlLine.startsWith("--")) {
                        if (sqlLine.endsWith(";")) {
                            sqlLine = sqlLine.substring(0, sqlLine.indexOf(";"));
                        }
                        Statement st = null;
                        try {
                            st = c.createStatement();
                            st.execute(sqlLine);
                        } catch (SQLException e) {
                            if (!"23000".equals(e.getSQLState())) {
                                LOG.warn("Failed to preload default report: " + sqlLine, e);
                            }
                        } catch (Exception e) {
                            LOG.warn("Failed to preload default report: " + sqlLine, e);
                        } finally {
                            if (st != null)
                                st.close();
                        }
                    }
                }

            } catch (HibernateException e) {
                LOG.error("Error while preloading default reports", e);
            } catch (Exception e) {
                LOG.error("Error while preloading default reports", e);
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                    }
                }
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (IOException e) {
                    }
                }
                if (c != null) {
                    c.close();
                }
            }
            return null;
        }
    };
    getHibernateTemplate().execute(hcb);
}

From source file:be.bittich.dynaorm.repository.GenericDynaRepository.java

@Override

public T findById(T t) {
    //get the primary keys
    Map<Field, PrimaryKey> fieldPrimary = getAnnotedFields(t, PrimaryKey.class);
    String req = dialect.selectAll(tableColumn.getTableName());
    try {//from   www .  j a  v  a 2  s.  co m
        //construct the request with parameters as a list of string(key is the request)
        KeyValue<String, List<String>> pkBuilt = conditionPrimaryKeysBuilder(t, fieldPrimary, dialect);
        //select * from T where ..
        req = req.concat(pkBuilt.getKey());
        T result = runner.query(req, getHandler(), pkBuilt.getValue().toArray());
        //just before returning the result
        if (result != null) {
            this.loadInvoker(result);
        }
        return result;
    } catch (SQLException ex) {
        Logger.getLogger(GenericDynaRepository.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
    } catch (RequestInvalidException ex) {
        Logger.getLogger(GenericDynaRepository.class.getName()).log(Level.SEVERE, null, ex);
    }
    throw new RuntimeException("Id Not found");
}

From source file:org.wso2.carbon.identity.core.persistence.IdentityDBInitializer.java

/**
 * executes given sql//  w  w w  . java  2  s.c o  m
 *
 * @param sql
 * @throws Exception
 */
private void executeSQL(String sql) {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    ResultSet resultSet = null;
    Connection conn = null;

    try {
        if (log.isDebugEnabled()) {
            log.debug("SQL : " + sql);
        }

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

        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        conn = dataSource.getConnection();
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) {
            // eliminating the table already exception for the derby and DB2 database types
            if (log.isDebugEnabled()) {
                log.info("Table Already Exists. Hence, skipping table creation");
            }
        } else {
            throw new IdentityRuntimeException("Error occurred while executing : " + sql, e);
        }
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing result set.", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing sql connection.", e);
            }
        }
    }
}