Example usage for java.sql SQLException getErrorCode

List of usage examples for java.sql SQLException getErrorCode

Introduction

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

Prototype

public int getErrorCode() 

Source Link

Document

Retrieves the vendor-specific exception code for this SQLException object.

Usage

From source file:com.versatus.jwebshield.securitylock.SecurityLockService.java

public SecurityLock processSecurityLock(int userId, String ip) throws SecurityLockException {
    QueryRunner run = new QueryRunner();
    Connection conn = null;/*w  ww  . j  ava 2s. co m*/
    SecurityLock al = null;

    List<Object> params = new ArrayList<Object>(3);

    try {
        conn = dbHelper.getConnection();

        al = checkSecurityLock(userId, ip);

        logger.debug("lockAccount: TriesToLock=" + getTriesToLock());

        int r = 0;

        if (al.getTryCounter() >= getTriesToLock() && !al.isLock()) {
            params.add(true);
            params.add(userId);
            params.add(ip);
            r = run.update(conn, setlockSql, params.toArray());
        } else {
            params.add(userId);
            params.add(ip);
            // params.add(false);
            r = run.update(conn, insertlockSql, params.toArray());
        }

        al = checkSecurityLock(userId, ip);

        logger.debug("lockAccount: response=" + r);

    } catch (SQLException e) {
        logger.error("lockAccount", e);
        logger.debug("lockAccount: ErrorCode=", e.getErrorCode());
        throw new SecurityLockException("Unable to access security lock database", e);
    } finally {

        try {
            DbUtils.close(conn);
        } catch (SQLException e) {
            // ignore
        }
    }
    return al;
}

From source file:Accounts.java

public void connectToDB() {
    try {/*from  w  ww .j  a  v a2 s . com*/
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
    } catch (SQLException connectException) {
        System.out.println(connectException.getMessage());
        System.out.println(connectException.getSQLState());
        System.out.println(connectException.getErrorCode());

    }
}

From source file:Accounts.java

private void displaySQLErrors(SQLException e) {
    errorText.append("SQLException: " + e.getMessage() + "\n");
    errorText.append("SQLState:     " + e.getSQLState() + "\n");
    errorText.append("VendorError:  " + e.getErrorCode() + "\n");
}

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

private boolean exportFile(final String id, final UserSession userSession, final HttpServletResponse response)
        throws IOException, SQLException, InternalErrorException {
    final Connection conn = db.getConnection();
    try {//from  w  w w .j a  va2  s .co  m
        final PreparedStatement stmt = StatementFormat.prepare(conn, "SELECT * FROM export WHERE id=?;", id);
        try {
            final ResultSet rs = stmt.executeQuery();
            try {
                if (!rs.next()) {
                    if (log.isDebugEnabled())
                        log.debug("failed to find file ID= " + id);
                    return false;
                }
                if (!userSession.getSessionId().equals(rs.getString("userSessionId"))) {
                    if (log.isTraceEnabled())
                        log.trace("invalid user session ID");
                    return false;
                }
                if (log.isTraceEnabled())
                    log.trace("exporting file " + id);
                response.reset();
                response.setBufferSize(DEFAULT_BUFFER_SIZE);
                response.setContentType(rs.getString("content_type"));
                if (rs.getBoolean("output_as_file")) {
                    // IMPORTANT:
                    // MUST be done before calling getOutputStream() otherwise no SaveAs dialogbox
                    response.setHeader("Content-Disposition",
                            MessageFormat.format("attachment; filename=\"{0}\"", rs.getString("name")));
                }
                IOUtils.copy(rs.getBinaryStream("content"), response.getOutputStream());
                /*   final BufferedInputStream input = new BufferedInputStream(rs.getBinaryStream("content"), DEFAULT_BUFFER_SIZE);
                   try {
                      final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
                      try {
                         final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                         int length;
                         while ((length = input.read(buffer)) > 0)
                output.write(buffer, 0, length);
                      } finally {
                         output.close();
                      }
                   } finally {
                      input.close();
                   }*/
            } finally {
                rs.close();
                try {
                    Database.executeUpdate(conn, "DELETE FROM export WHERE id=?;", id);
                } catch (final SQLException e) {
                    if (log.isErrorEnabled())
                        log.error("failed to delete export record: " + e.getErrorCode() + "-" + e.getSQLState(),
                                e);
                }
            }
        } finally {
            stmt.close();
        }
    } finally {
        // remove any orphan export records i.e. older than 48h (beware of timezone!)
        final Calendar dt = Util.dateToCalendar(new Date());
        dt.add(GregorianCalendar.DATE, -2);
        try {
            Database.executeUpdate(conn, "DELETE FROM export WHERE created < ?;", Util.calendarToSqlDate(dt));
        } catch (final SQLException __) {
        }
        conn.close();
    }
    return true;
}

From source file:com.nabla.wapp.server.database.UpdateStatement.java

public void execute(final Connection conn, final T record)
        throws SQLException, DispatchException, ValidationException {
    Assert.argumentNotNull(conn);/*from  ww  w .  ja  v a  2 s  .c  om*/

    final List<IStatementParameter> parametersToUpdate = new ArrayList<IStatementParameter>();
    final ArgumentList updates = new ArgumentList();
    for (IStatementParameter parameter : parameters) {
        if (!parameter.include(record))
            continue;
        parametersToUpdate.add(parameter);
        updates.add(parameter.getName() + "=?");
    }
    if (parametersToUpdate.isEmpty()) {
        if (log.isDebugEnabled())
            log.debug("no values to update");
        return;
    }
    final String sql = MessageFormat.format(sqlTemplate, updates.toString());
    if (log.isDebugEnabled())
        log.debug("SQL=" + sql);
    final PreparedStatement stmt = conn.prepareStatement(sql);
    try {
        int i = 1;
        for (IStatementParameter parameter : parametersToUpdate)
            parameter.write(stmt, i++, record);
        recordId.write(stmt, i++, record);
        if (stmt.executeUpdate() != 1)
            throw new DispatchException(CommonServerErrors.RECORD_HAS_BEEN_REMOVED);
    } catch (final SQLException e) {
        if (uniqueFieldName != null && SQLState.valueOf(e) == SQLState.INTEGRITY_CONSTRAINT_VIOLATION) {
            if (log.isErrorEnabled())
                log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e);
            throw new ValidationException(uniqueFieldName, CommonServerErrors.DUPLICATE_ENTRY);
        }
        throw e;
    } finally {
        Database.close(stmt);
    }
}

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

/**
 * Constructor//from   w ww.  jav  a 2  s  .c om
 * @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:com.nabla.wapp.server.database.InsertStatement.java

public int execute(final Connection conn, final T record)
        throws SQLException, ValidationException, InternalErrorException {
    Assert.argumentNotNull(conn);//from w  w w. j  a  v  a 2s .  c o  m

    final List<IStatementParameter> parametersToInsert = new ArrayList<IStatementParameter>();
    final ArgumentList names = new ArgumentList();
    final ArgumentList values = new ArgumentList();
    for (IStatementParameter parameter : parameters) {
        if (!parameter.include(record))
            continue;
        parametersToInsert.add(parameter);
        names.add(parameter.getName());
        values.add("?");
    }
    if (parametersToInsert.isEmpty()) {
        if (log.isErrorEnabled())
            log.error("no values to insert!!!!");
        throw new InternalErrorException(
                Util.formatInternalErrorDescription("no parameter values given for SQL statement"));
    }
    final String sql = MessageFormat.format(sqlTemplate, names.toString(), values.toString());
    if (log.isDebugEnabled())
        log.debug("SQL=" + sql);
    final PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    try {
        int i = 1;
        for (IStatementParameter parameter : parametersToInsert)
            parameter.write(stmt, i++, record);
        if (stmt.executeUpdate() != 1) {
            if (log.isErrorEnabled())
                log.error("failed to add record");
            throw new InternalErrorException(
                    Util.formatInternalErrorDescription("failed to execute SQL statement"));
        }
        final ResultSet rsKey = stmt.getGeneratedKeys();
        try {
            rsKey.next();
            return rsKey.getInt(1);
        } finally {
            Database.close(rsKey);
        }
    } catch (final SQLException e) {
        if (uniqueFieldName != null && SQLState.valueOf(e) == SQLState.INTEGRITY_CONSTRAINT_VIOLATION) {
            if (log.isErrorEnabled())
                log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e);
            throw new ValidationException(uniqueFieldName, CommonServerErrors.DUPLICATE_ENTRY);
        }
        throw e;
    } finally {
        Database.close(stmt);
    }
}

From source file:com.zimbra.cs.db.MySQL.java

@Override
boolean compareError(SQLException e, Db.Error error) {
    Integer code = mErrorCodes.get(error);
    return (code != null && e.getErrorCode() == code);
}

From source file:database.DataBaseMySQL.java

public ResultSet get(String quary) {

    ResultSet res;//from  w  ww  . j a  v a2s.  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:database.DataBaseMySQL.java

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

    ResultSet res;/*from  www.  jav a2s  .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;

}