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

The following examples show how to use java.sql.SQLException#getErrorCode() . 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
Source File: FailoverProxy.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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
Source File: SqlExceptionTranslator.java    From spacewalk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: TestReservedWords.java    From jaybird with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 4
Source File: CustomSqlExceptionTranslator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
	if (ex.getErrorCode() == 2) {
		return new TransientDataAccessResourceException("Custom", ex);
	}
	return null;
}
 
Example 5
Source File: ConnectionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 6
Source File: TestPreStartedMasterServer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 *
 *
 * @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 7
Source File: AbstractMastersListener.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 8
Source File: 1205753_EmbedPooledConnection_0_t.java    From coming with MIT License 5 votes vote down vote up
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 9
Source File: OracleExceptionTransformer.java    From Carbonado with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: ReplicationRun_Local_StateTest_part1.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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 11
Source File: SybaseExceptionRecognizer.java    From dekaf with 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 12
Source File: MySQLBaseDAO.java    From conductor with 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 13
Source File: 1205753_EmbedPooledConnection_0_s.java    From coming with MIT License 5 votes vote down vote up
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
Source File: OracleExceptionTransformer.java    From Carbonado with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: GfxdServerLauncher.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: CrDbRetryInterceptor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
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 17
Source File: SybaseDatabaseType.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public boolean violatesUniqueIndexWithoutRecursion(SQLException sqlException)
{
    return CODE_DUPLICATE == sqlException.getErrorCode();
}
 
Example 18
Source File: OracleEnvironmentHandler.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
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 19
Source File: GenericQuery.java    From gemfirexd-oss with 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 20
Source File: MasterProtocol.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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");
}