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

The following examples show how to use java.sql.SQLException#getErrorCode() . 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 check out the related API usage on the sidebar.
Example 1
/**
 * Add Host information ("on HostAddress...") to exception.
 *
 * <p>example : java.sql.SQLException: (conn=603) Cannot execute statement in a READ ONLY
 * transaction.<br>
 * Query is: INSERT INTO TableX VALUES (21)<br>
 * on HostAddress{host='mydb.example.com', port=3306},master=true
 *
 * @param exception current exception
 * @param protocol protocol to have hostname
 */
private static SQLException addHostInformationToException(
    SQLException exception, Protocol protocol) {
  if (protocol != null) {
    return new SQLException(
        exception.getMessage()
            + "\non "
            + protocol.getHostAddress().toString()
            + ",master="
            + protocol.isMasterConnection(),
        exception.getSQLState(),
        exception.getErrorCode(),
        exception.getCause());
  }
  return exception;
}
 
Example 2
@Test
public void checkReservedWords() throws Exception {
    try (Connection connection = getConnectionViaDriverManager();
         Statement stmt = connection.createStatement()) {
        int count = 1;
        for (String keyword : RESERVED_WORDS) {
            try {
                stmt.execute("create table table" + (++count) + " ( " + keyword + " integer)");
                System.out.println("Keyword \"" + keyword + "\" is not a reserved word");
            } catch (SQLException e) {
                //System.out.println("Failed for reserved word " + keyword);
                if (e.getErrorCode() != ISCConstants.isc_dsql_token_unk_err) {
                    e.printStackTrace();
                }
                // ignore
            }
        }
    }
}
 
Example 3
/**
 * Convert from SQLException to some other Exception type
 * @param e The SQLException to translate
 * @return The translated RuntimeException, which includes a reference
 *         to the SQLException that was passed in.
 */
private static RuntimeException oracleSQLException(SQLException e) {
    int code = e.getErrorCode();
    String msg = e.getMessage();
    switch(code) {
        case 1:
            int ind = msg.indexOf('(') + 1;
            String desc = msg.substring(ind, msg.indexOf(')', ind));
            return new ConstraintViolationException(
                         ExceptionConstants.VALUE_TOO_LARGE, desc, msg, e);
        case 1401:
        case 12899:
            return new ConstraintViolationException(
                         ExceptionConstants.VALUE_TOO_LARGE, null, msg, e);
        default:
            return new WrappedSQLException(e.getMessage(), e);
    }
}
 
Example 4
protected boolean isTransactionRetryException(Throwable exception) {
    if (exception instanceof SQLException) {
        SQLException sqlException = (SQLException) exception;
        if (sqlException.getErrorCode() == 40001 || (sqlException.getMessage() != null && sqlException.getMessage().contains("retry txn"))) {
            return true;
        }
    }

    if (exception.getCause() != null) {
        if (isTransactionRetryException(exception.getCause())) {
            return true;
        }
    }
    return false;
}
 
Example 5
@Override
protected void disconnect(Cache cache) {
  Exception severeEx = null;
  try {
    getFabricServiceInstance().stop(this.bootProps);
  } catch (SQLException se) {
    if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState())))) {
      // we got the expected exception
    }
    else {
      severeEx = se;
    }
  } catch (Exception ex) {
    // got an unexpected exception
    severeEx = ex;
  } finally {
    if (severeEx != null) {
      // if the error code or SQLState is different, we have
      // an unexpected exception (shutdown failed)
      String msg = LocalizedResource.getMessage("FS_JDBC_SHUTDOWN_ERROR");
      logSevere(msg, severeEx);
    }
    if (!cache.isClosed()) {
      cache.close();
    }
  }
}
 
Example 6
@Override
public boolean isUniqueConstraintError(SQLException e) {
    if (isConstraintError(e)) {
        String sqlstate = e.getSQLState();
        int errorCode = e.getErrorCode();
        return UNIQUE_CONSTRAINT_VIOLATION == errorCode
            || SQLSTATE_UNIQUE_CONSTRAINT_VIOLATION.equals(sqlstate);
    }
    return false;
}
 
Example 7
public synchronized void notifyError(SQLException exception)
{
	// only report fatal error to the connection pool manager 
	if (exception.getErrorCode() < ExceptionSeverity.SESSION_SEVERITY)
		return;
 
	// tell my listeners an exception is about to be thrown
       fireConnectionEventListeners(exception);
}
 
Example 8
Source Project: conductor   File: MySQLBaseDAO.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isDeadLockError(Throwable throwable){
    SQLException sqlException = findCauseSQLException(throwable);
    if (sqlException == null){
        return false;
    }
    return ER_LOCK_DEADLOCK == sqlException.getErrorCode();
}
 
Example 9
Source Project: dekaf   File: SybaseExceptionRecognizer.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected DBException recognizeSpecificException(@NotNull final SQLException sqle,
                                                 @Nullable final String statementText) {
  int errCode = sqle.getErrorCode();
  if (errCode > 0) {
    return recognizeForJTDS(sqle, statementText, errCode);
  }
  String state = sqle.getSQLState();
  if (state != null && !state.isEmpty()) {
    return recognizeForNative(sqle, statementText, state);
  }
  return null;
}
 
Example 10
@Override
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
	if (ex.getErrorCode() == 2) {
		return new TransientDataAccessResourceException("Custom", ex);
	}
	return null;
}
 
Example 11
private void _testPreStartedMasterServer()
{
    Connection conn = null;
    String db = masterDatabasePath +FS+ReplicationRun.masterDbSubPath +FS+ replicatedDb;
    String connectionURL = "jdbc:derby:"
            + "//" + masterServerHost + ":" + masterServerPort + "/"
            + db
            + ";startMaster=true"
            + ";slavehost=" + slaveServerHost
            + ";slaveport=" + slaveServerPort;
    util.DEBUG("testPreStartedMasterServer: " + connectionURL);
    try
    {
        conn = DriverManager.getConnection(connectionURL);
    }
    catch (SQLException se)
    {
        int ec = se.getErrorCode();
        String ss = se.getSQLState();
        String msg = ec + " " + ss + " " + se.getMessage();
        util.DEBUG("testStartMasterConnect_Illegal: " + msg);
        assertTrue("Unexpected SQLException: " + msg, "08001".equals(ss));
        util.DEBUG("As expected.");
        return;
    }
    assertTrue("Expected SQLException: '08001 " + db + "'",false);
}
 
Example 12
@Override
public boolean isDeadlockError(SQLException e) {
    if (super.isDeadlockError(e)) {
        return true;
    }
    if (e != null) {
        int errorCode = e.getErrorCode();
        return DEADLOCK_DETECTED == errorCode;
    }
    return false;
}
 
Example 13
public synchronized void notifyError(SQLException exception)
{
	// only report fatal error to the connection pool manager 
	if (exception.getErrorCode() < ExceptionSeverity.SESSION_SEVERITY)
		return;
 
	// tell my listeners an exception is about to be thrown
       fireConnectionEventListeners(exception);
}
 
Example 14
/**
 * Call when a failover is detected on master connection. Will :
 *
 * <ol>
 *   <li>set fail variable
 *   <li>try to reconnect
 *   <li>relaunch query if possible
 * </ol>
 *
 * @param method called method
 * @param args methods parameters
 * @param protocol current protocol
 * @return a HandleErrorResult object to indicate if query has been relaunched, and the exception
 *     if not
 * @throws SQLException when method and parameters does not exist.
 */
public HandleErrorResult handleFailover(
    SQLException qe, Method method, Object[] args, Protocol protocol, boolean isClosed)
    throws SQLException {
  if (isExplicitClosed()) {
    throw new SQLException("Connection has been closed !");
  }
  if (setMasterHostFail()) {
    logger.warn(
        "SQL Primary node [{}, conn={}, local_port={}, timeout={}] connection fail. Reason : {}",
        this.currentProtocol.getHostAddress().toString(),
        this.currentProtocol.getServerThreadId(),
        this.currentProtocol.getSocket().getLocalPort(),
        this.currentProtocol.getTimeout(),
        qe.getMessage());
    addToBlacklist(currentProtocol.getHostAddress());
  }

  // check that failover is due to kill command
  boolean killCmd =
      qe != null
          && qe.getSQLState() != null
          && qe.getSQLState().equals("70100")
          && 1927 == qe.getErrorCode();

  return primaryFail(method, args, killCmd, isClosed);
}
 
Example 15
/**
 *
 *
 * @throws SQLException, IOException, InterruptedException
 */
public void testStartMasterConnect_Illegal()
throws SQLException, IOException, InterruptedException
{
    System.out.println("**** TestPreStartedMasterServer.testStartMasterConnect_Illegal() "+
            getTestConfiguration().getJDBCClient().getJDBCDriverName());
    
    Connection conn = null;
    String db = masterDatabasePath +"/"+ReplicationRun.masterDbSubPath +"/"+ replicatedDb;
    String connectionURL = "jdbc:derby:" 
            + "//" + masterServerHost + ":" + masterServerPort + "/"
            + db
            + ";startMaster=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("testStartMasterConnect_Illegal: " + msg);
        // 40000 08001
        assertSQLState("Unexpected SQLException: " + msg, "08001", se);
        return;
    }
    assertTrue("Expected SQLException: '-4499 08001 " + db + "'",false);
}
 
Example 16
/**
 * Resets a default auto-commit value of 0 to 1, as required by JDBC specification.
 * Takes into account that the default auto-commit value of 0 may have been changed on the server via init_connect.
 */
private void handleAutoCommitDefaults() throws SQLException {
    boolean resetAutoCommitDefault = false;

    // Server Bug#66884 (SERVER_STATUS is always initiated with SERVER_STATUS_AUTOCOMMIT=1) invalidates "elideSetAutoCommits" feature.
    // TODO Turn this feature back on as soon as the server bug is fixed. Consider making it version specific.
    // if (!getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_elideSetAutoCommits).getValue()) {
    String initConnectValue = this.session.getServerSession().getServerVariable("init_connect");
    if (initConnectValue != null && initConnectValue.length() > 0) {
        // auto-commit might have changed

        String s = this.session.queryServerVariable("@@session.autocommit");
        if (s != null) {
            this.session.getServerSession().setAutoCommit(Boolean.parseBoolean(s));
            if (!this.session.getServerSession().isAutoCommit()) {
                resetAutoCommitDefault = true;
            }
        }

    } else {
        // reset it anyway, the server may have been initialized with --autocommit=0
        resetAutoCommitDefault = true;
    }
    //} else if (getSession().isSetNeededForAutoCommitMode(true)) {
    //    // we're not in standard autocommit=true mode
    //    this.session.setAutoCommit(false);
    //    resetAutoCommitDefault = true;
    //}

    if (resetAutoCommitDefault) {
        try {
            setAutoCommit(true); // required by JDBC spec
        } catch (SQLException ex) {
            if (ex.getErrorCode() != MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD || this.disconnectOnExpiredPasswords.getValue()) {
                throw ex;
            }
        }
    }
}
 
Example 17
Source Project: reladomo   File: SybaseDatabaseType.java    License: Apache License 2.0 4 votes vote down vote up
public boolean violatesUniqueIndexWithoutRecursion(SQLException sqlException)
{
    return CODE_DUPLICATE == sqlException.getErrorCode();
}
 
Example 18
Source Project: gemfirexd-oss   File: GenericQuery.java    License: Apache License 2.0 4 votes vote down vote up
public void  executeQueries(boolean prepare,boolean verbose) throws SQLException{
	rowsExpected=new int[queries.size()]; //initialize the array with correct size
	String query="";
	if(prepare){	
		if (verbose)
			System.out.println("=====================> Using java.sql.PreparedStatement <====================");					
	}else{
		if (verbose)
			System.out.println("=====================> Using java.sql.Statement <====================");
		
	}
	try{
		for(int k=0;k<queries.size();k++){
			
			query=(String)queries.get(k);
			String [] times=new String [StaticValues.ITER];
			int rowsReturned=0;
			for (int i=0;i<StaticValues.ITER;i++){ 
				
				Statement stmt=null;
				ResultSet rs=null;
				PreparedStatement pstmt=null;
				if(prepare){	
					pstmt=conn.prepareStatement(query);					
				}else{
					stmt=conn.createStatement();
					
				}
				long start=System.currentTimeMillis();
				if(prepare)
					rs=pstmt.executeQuery();
				else
					rs=stmt.executeQuery(query);
				ResultSetMetaData rsmd=rs.getMetaData();
				int totalCols=rsmd.getColumnCount();
				
				while(rs.next()){
					String row="";
					for(int j=1;j<=totalCols;j++){
						row+=rs.getString(j)+" | ";
					}
					rowsReturned++;
				}
				long time_taken=(System.currentTimeMillis() - start);
				if (verbose){
					System.out.println("Time required to execute:");
					System.out.println(query);
					System.out.println("Total Rows returned = "+rowsReturned);
				
					System.out.println("==> "+time_taken+" milliseconds "+" OR "+TestUtils.getTime(time_taken));
						times[i]=TestUtils.getTime(time_taken);
				}
				rs.close();
				if(prepare){
					pstmt.close();
				}else{
					stmt.close();
				}
				rowsExpected[k]=rowsReturned;//add expected rows for respective queries
				rowsReturned=0;
			}//end for loop to run StaticValues.ITER times
			
			if(prepare){	
				prepStmtRunResults.add(times);
			}else{
				stmtRunResults.add(times);
			}
			
		}
	}catch(SQLException sqe){
		throw new SQLException("Failed query:\n "+query+"\n SQLState= "+sqe.getSQLState()+"\n ErrorCode= "+sqe.getErrorCode()+"\n Message= "+sqe.getMessage());
	}
}
 
Example 19
private Map<String, List<String>> getForeignKeys( String owner, String tableName, Connection connection ) {

        String query = "select table_name, constraint_name "
                       + " from all_constraints "
                       + " where r_owner = '" + owner + "' "
                       + " and constraint_type = 'R' "
                       + " and r_constraint_name in "
                       + " ( select constraint_name from all_constraints "
                       + " where constraint_type in ('P', 'U') "
                       + " and table_name = '" + tableName + "'"
                       + " and owner = '" + owner + "' )";

        PreparedStatement stmnt = null;
        Map<String, List<String>> tableForeignKey = new HashMap<String, List<String>>();
        ResultSet rs = null;
        try {
            if (log.isTraceEnabled()) {
                log.trace("Executing SQL query: " + query);
            }
            stmnt = connection.prepareStatement(query);
            rs = stmnt.executeQuery();
            while (rs.next()) {
                String parentTableName = rs.getString("TABLE_NAME");
                String fKeyName = rs.getString("CONSTRAINT_NAME");

                if (tableForeignKey.containsKey(parentTableName)) {
                    tableForeignKey.get(parentTableName).add(fKeyName);
                } else {
                    List<String> fKeys = new ArrayList<String>();
                    fKeys.add(fKeyName);
                    tableForeignKey.put(parentTableName, fKeys);
                }
            }

            return tableForeignKey;
        } catch (SQLException e) {
            throw new DbException(
                                  "SQL errorCode=" + e.getErrorCode() + " sqlState=" + e.getSQLState() + " "
                                  + e.getMessage(), e);
        } finally {
            DbUtils.closeStatement(stmnt);
        }
    }
 
Example 20
/**
 * loop until found the failed connection.
 *
 * @param listener current failover
 * @param globalInfo server global variables information
 * @param addresses list of HostAddress to loop
 * @param searchFilter search parameter
 * @throws SQLException if not found
 */
public static void loop(
    Listener listener,
    final GlobalStateInfo globalInfo,
    final List<HostAddress> addresses,
    SearchFilter searchFilter)
    throws SQLException {

  MasterProtocol protocol;
  ArrayDeque<HostAddress> loopAddresses = new ArrayDeque<>(addresses);
  if (loopAddresses.isEmpty()) {
    resetHostList(listener, loopAddresses);
  }

  int maxConnectionTry = listener.getRetriesAllDown();
  boolean firstLoop = true;
  SQLException lastQueryException = null;
  while (!loopAddresses.isEmpty() || (!searchFilter.isFailoverLoop() && maxConnectionTry > 0)) {
    protocol = getNewProtocol(listener.getProxy(), globalInfo, listener.getUrlParser());

    if (listener.isExplicitClosed()) {
      return;
    }
    maxConnectionTry--;

    try {
      HostAddress host = loopAddresses.pollFirst();
      if (host == null) {
        loopAddresses.addAll(listener.getUrlParser().getHostAddresses());
        host = loopAddresses.pollFirst();
      }
      protocol.setHostAddress(host);
      protocol.connect();
      if (listener.isExplicitClosed()) {
        protocol.close();
        return;
      }
      listener.removeFromBlacklist(protocol.getHostAddress());
      listener.foundActiveMaster(protocol);
      return;

    } catch (SQLException e) {
      listener.addToBlacklist(protocol.getHostAddress());
      lastQueryException = e;
    }

    // if server has try to connect to all host, and master still fail
    // add all servers back to continue looping until maxConnectionTry is reached
    if (loopAddresses.isEmpty() && !searchFilter.isFailoverLoop() && maxConnectionTry > 0) {
      resetHostList(listener, loopAddresses);
      if (firstLoop) {
        firstLoop = false;
      } else {
        try {
          // wait 250ms before looping through all connection another time
          Thread.sleep(250);
        } catch (InterruptedException interrupted) {
          // interrupted, continue
        }
      }
    }
  }
  if (lastQueryException != null) {
    throw new SQLException(
        "No active connection found for master : " + lastQueryException.getMessage(),
        lastQueryException.getSQLState(),
        lastQueryException.getErrorCode(),
        lastQueryException);
  }
  throw new SQLException("No active connection found for master");
}