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:org.wso2.carbon.apimgt.migration.client.MigrationDBCreator.java

private void executeSQL(String sql) throws APIMigrationException {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;//  w  w w .  ja v a  2 s . com
    }

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

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

        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        SQLWarning warning = connection.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        connection.clearWarnings();
    } catch (SQLException e) {
        if ("X0Y32".equals(e.getSQLState()) || "42710".equals(e.getSQLState())) {
            // 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 APIMigrationException("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);
            }
        }
    }
}

From source file:org.sp.tests.connectors.rdbms.transactions.RDBMSTransactions.java

@BeforeClass(alwaysRun = true)
public void initializeTables() {
    String createPersonLKTable = "CREATE TABLE personsinlanka (\n" + "    personid int NOT NULL,\n"
            + "    lastname varchar(255) NOT NULL,\n" + "    firstname varchar(255),\n"
            + "    address varchar(255),\n" + "    city varchar(255),\n" + "    PRIMARY KEY (personid)\n"
            + ");";
    String createPersonsUSTable = "CREATE TABLE personsinus (\n" + "    personid int NOT NULL,\n"
            + "    lastname varchar(255) NOT NULL,\n" + "    firstname varchar(255),\n"
            + "    address varchar(255),\n" + "    city varchar(255),\n" + "    PRIMARY KEY (personid)\n"
            + ");";

    try {/*  w ww  .j a v  a  2 s.c  om*/
        conn = DriverManager.getConnection("jdbc:mysql://" + mysqlURL + "?" + "user=" + Constants.MYSQL_USERNAME
                + "&password=" + Constants.MYSQL_PASSWORD);

        stmt = conn.createStatement();
        stmt.executeUpdate(createPersonLKTable);
        stmt.executeUpdate(createPersonsUSTable);

    } catch (SQLException ex) {
        log.error("SQLException: " + ex.getMessage());
        log.error("SQLState: " + ex.getSQLState());
        log.error("VendorError: " + ex.getErrorCode());
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqlEx) {
            }
        }
    }
}

From source file:com.nabla.wapp.server.basic.general.ExportService.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final String id = request.getParameter("id");
    if (id == null || id.isEmpty()) {
        if (log.isTraceEnabled())
            log.trace("missing file ID");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;//ww w.  ja  v a2 s.c  o m
    }
    final UserSession userSession = UserSession.load(request);
    if (userSession == null) {
        if (log.isTraceEnabled())
            log.trace("missing user session");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    try {
        if (exportFile(id, userSession, response)) {
            //   response.setStatus(HttpServletResponse.SC_OK);
        } else
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (final SQLException e) {
        if (log.isErrorEnabled())
            log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (final Throwable e) {
        if (log.isErrorEnabled())
            log.error("unexpected error", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.emr.utilities.DatabaseManager.java

/**
 * Constructor//from   w  w w .ja  va 2 s .c  o m
 * @param servername {@link String} Server name
 * @param port {@link String} Server Mysql Port
 * @param dbName {@link String} Database name
 * @param username {@link String} Mysql Username
 * @param password {@link String} Password
 */
public DatabaseManager(String servername, String port, String dbName, String username, String password) {
    this.servername = servername;
    this.port = port;
    this.url = "jdbc:mysql://" + servername + ":" + port + "/";
    this.dbName = dbName;
    this.userName = username;
    this.password = password;
    this.driver = "com.mysql.jdbc.Driver";
    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url + dbName, userName, password);
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
        JOptionPane.showMessageDialog(null, "SQLException: " + ex.getMessage(), "Exception!",
                JOptionPane.ERROR_MESSAGE);
    } catch (ClassNotFoundException cs) {
        System.out.println("Class not found: " + cs.getMessage());
        JOptionPane.showMessageDialog(null, "Class not found: " + cs.getMessage(), "Exception!",
                JOptionPane.ERROR_MESSAGE);
    } catch (InstantiationException | IllegalAccessException i) {
        System.out.println("Instantiation/Illegal State Error: " + i.getMessage());
        JOptionPane.showMessageDialog(null, "Instantiation/Illegal State Error: " + i.getMessage(),
                "Exception!", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:database.DataBaseMySQL.java

public ResultSet get(String quary) {

    ResultSet res;//from   ww  w . j a va  2 s .  c  o m
    Statement stmt;

    try {

        stmt = conn.createStatement();
        res = stmt.executeQuery(quary);

        return res;

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

    return res = null;

}

From source file:eu.optimis.mi.monitoring_manager.test.MonitoringManagerTest.java

private boolean deleteResources(String type) {
    DBConnection dbconn = new DBConnection();
    Connection conn = dbconn.getConnection();

    String query;//from  w ww . j  av  a2s  .c  o  m
    if (type.equals("physical"))
        query = "Delete FROM monitoring_resource_physical where physical_resource_id like '%UnitTest%'";
    else
        query = "Delete FROM monitoring_resource_virtual where virtual_resource_id like '%UnitTest%'";
    try {
        Statement st = conn.createStatement();
        st.executeUpdate(query);

    } catch (SQLException e) {
        logger.error("SQLException:" + e.getMessage() + ":" + e.getSQLState());
        return false;
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
    return true;
}

From source file:eu.optimis.aggregator.test.AggregatorPushTest.java

private boolean deleteResources() {
    DBConnection dbconn = new DBConnection();
    Connection conn = dbconn.getConnection();
    String queryPhysical = null;/* ww w .  java 2  s.co  m*/
    String queryVirtual = null;
    queryPhysical = "Delete FROM  monitoring_resource_physical where physical_resource_id like '" + "%UnitTest%"
            + "'";
    queryVirtual = "Delete FROM  monitoring_resource_virtual where virtual_resource_id like '" + "%UnitTest%"
            + "'";
    try {
        Statement st = conn.createStatement();
        st.executeUpdate(queryPhysical);
        st.executeUpdate(queryVirtual);

    } catch (SQLException e) {
        logger.error("SQLException:" + e.getMessage() + ":" + e.getSQLState());
        return false;
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
        ;
    }
    return true;
}

From source file:org.apache.sqoop.mapreduce.SQLServerExportDBExecThread.java

/**
 * Execute the provided PreparedStatement, by default this assume batch
 * execute, but this can be overridden by subclasses for a different mode
 * of execution which should match getPreparedStatement implementation
 *//* www .  ja  va 2  s. c o  m*/
@Override
protected void executeStatement(PreparedStatement stmt, List<SqoopRecord> records) throws SQLException {
    // On failures in commit step, we cannot guarantee that transactions have
    // been successfully committed to the database.
    // This can result in access violation issues for columns with unique
    // constraints.
    // One way to handle this is check whether records are committed in the
    // database before propagating the failure for retry. However in case we
    // have connection loss, we wont be able to access the database.
    // An alternative option is to ignore violation issues in the next retry
    // in case the records have been already committed

    Connection conn = getConnection();
    try {
        stmt.executeBatch();
    } catch (SQLException execSqlEx) {
        LOG.warn("Error executing statement: " + execSqlEx);
        if (failedCommit && canIgnoreForFailedCommit(execSqlEx.getSQLState())) {
            LOG.info("Ignoring error after failed commit");
        } else {
            throw execSqlEx;
        }
    }

    // If the batch of records is executed successfully, then commit before
    // processing the next batch of records
    try {
        conn.commit();
        failedCommit = false;
    } catch (SQLException commitSqlEx) {
        LOG.warn("Error while committing transactions: " + commitSqlEx);

        failedCommit = true;
        throw commitSqlEx;
    }
}

From source file:database.DataBaseMySQL.java

public ResultSet get(String[] keys, String t_name) {

    ResultSet res;//  w w w  . j av  a  2 s .com
    Statement stmt;

    String query = "select ";

    for (int i = 0; i < keys.length; i++) {

        query = query + keys[i] + " ,";
    }

    query = query.replace(query.substring(query.length() - 1), "");
    query = query + "from " + t_name;

    System.out.println(query);

    try {

        stmt = conn.createStatement();
        res = stmt.executeQuery(query);

        return res;
        /*
         while (res.next()) {
         int id = res.getInt("id");
         String title = res.getString("title");
         System.out.println("Get value from kay's :"+title);
                
         }
         */

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

    return res = null;

}