Example usage for java.sql PreparedStatement getGeneratedKeys

List of usage examples for java.sql PreparedStatement getGeneratedKeys

Introduction

In this page you can find the example usage for java.sql PreparedStatement getGeneratedKeys.

Prototype

ResultSet getGeneratedKeys() throws SQLException;

Source Link

Document

Retrieves any auto-generated keys created as a result of executing this Statement object.

Usage

From source file:edu.pitt.apollo.db.ApolloDbUtils.java

public BigInteger[] addSimulationRun(RunMessage runMessage, int md5CollisionId,
        SoftwareIdentification identificationOfSoftwareToRun, int sourceSoftwareIdKey,
        SoftwareIdentification destinationSoftwareForRunSimulationMessage, Authentication authentication)
        throws ApolloDatabaseException, Md5UtilsException {

    String userName = authentication.getRequesterId();
    String password = authentication.getRequesterPassword();

    runMessage.setAuthentication(new Authentication());

    String[] userIdTokens = parseUserId(userName);
    userName = userIdTokens[0];//from   w  w w  .j a va  2  s  .co  m

    Integer softwareKey = null;
    if (identificationOfSoftwareToRun != null) {
        softwareKey = getSoftwareIdentificationKey(identificationOfSoftwareToRun);
    }
    int userKey = getUserKey(userName, password);

    BigInteger simulationGroupId = null;
    String additionalInsertField = "";
    String additionalParamHolder = "";
    BigInteger[] runIdSimulationGroupId = new BigInteger[2];
    String md5 = md5Utils.getMd5(runMessage);

    try (Connection conn = datasource.getConnection()) {

        simulationGroupId = getNewSimulationGroupId();
        runIdSimulationGroupId[1] = simulationGroupId;
        additionalInsertField = ", simulation_group_id";
        additionalParamHolder = ",?";

        String query = "INSERT IGNORE INTO run (md5_hash_of_run_message, software_id, requester_id, last_service_to_be_called, md5_collision_id "
                + additionalInsertField + ") VALUES (?, ?, ?, ?, ? " + additionalParamHolder + ")";
        PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, md5);
        if (softwareKey != null) {
            pstmt.setInt(2, softwareKey);
        } else {
            pstmt.setNull(2, Types.INTEGER);
        }
        pstmt.setInt(3, userKey);
        pstmt.setInt(4, 1);
        pstmt.setInt(5, md5CollisionId);
        pstmt.setLong(6, simulationGroupId.longValue());

        ResultSet rs;
        int rowsAffected = pstmt.executeUpdate();

        if (rowsAffected > 0) {
            rs = pstmt.getGeneratedKeys();
        } else {
            query = "SELECT id FROM run WHERE md5_hash_of_run_message = ? and md5_collision_id = ?";
            pstmt = conn.prepareStatement(query);
            pstmt.setString(1, md5);
            pstmt.setInt(2, md5CollisionId);
            rs = pstmt.executeQuery();
        }

        BigInteger runId;
        if (rs.next()) {
            runId = new BigInteger(rs.getString(1));
        } else {
            throw new ApolloDatabaseRecordNotInsertedException("Record not inserted!");
        }

        List<BigInteger> runIds = new ArrayList<>();
        runIds.add(runId);
        if (!(runMessage instanceof RunSimulationsMessage)) {
            addRunIdsToSimulationGroup(simulationGroupId, runIds);
        }

        // ALSO NEED TO ADD serialized runSimulationMessage(JSON) to
        // run_data_content table...
        // use insertDataContentForRun for this
        int dataContentKey = addTextDataContent(jsonUtils.getJSONString(runMessage));
        int runDataDescriptionId = getRunDataDescriptionId(ContentDataFormatEnum.TEXT, "run_message.json",
                ContentDataTypeEnum.RUN_MESSAGE, sourceSoftwareIdKey,
                getSoftwareIdentificationKey(destinationSoftwareForRunSimulationMessage));
        // int runDataId = the following line returns the runDataId, but
        // it's not used at this point.
        associateContentWithRunId(new BigInteger(String.valueOf(runId)), dataContentKey, runDataDescriptionId);

        runIdSimulationGroupId[0] = runId;
        if (runIdSimulationGroupId.length == 2) {
            runIdSimulationGroupId[1] = simulationGroupId;
        }

        updateStatusOfRun(runId, MethodCallStatusEnum.LOADED_RUN_CONFIG_INTO_DATABASE,
                "Adding config information to the database for runId: " + runId.toString());

        return runIdSimulationGroupId;
        // } catch (ClassNotFoundException ex) {
        //     throw new ApolloDatabaseException(
        //             "ClassNotFoundException attempting to add simulation run: "
        //                     + ex.getMessage());
    } catch (SQLException ex) {
        throw new ApolloDatabaseException("SQLException attempting to add simulation run: " + ex.getMessage());
    }
}

From source file:org.wso2.appcloud.core.dao.ApplicationDAO.java

/**
 * Method for adding container./* w w w .  j a  va  2s .  c o m*/
 *
 * @param dbConnection database connection
 * @param container    container object
 * @param deploymentId id of deployment
 * @param tenantId     id of tenant
 * @throws AppCloudException
 */
public void addContainer(Connection dbConnection, Container container, int deploymentId, int tenantId)
        throws AppCloudException {

    PreparedStatement preparedStatement = null;

    try {
        int containerId = -1;
        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_CONTAINER,
                Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, container.getImageName());
        preparedStatement.setString(2, container.getImageVersion());
        preparedStatement.setInt(3, deploymentId);
        preparedStatement.setInt(4, tenantId);

        preparedStatement.execute();

        ResultSet resultSet = preparedStatement.getGeneratedKeys();
        if (resultSet.next()) {
            containerId = resultSet.getInt(1);
        }
        for (ContainerServiceProxy containerServiceProxy : container.getServiceProxies()) {
            addContainerServiceProxy(dbConnection, containerServiceProxy, containerId, tenantId);
        }

    } catch (SQLException e) {
        String msg = "Error while inserting deployment container record in tenant : " + tenantId;
        throw new AppCloudException(msg, e);
    } finally {
        DBUtil.closePreparedStatement(preparedStatement);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * Register configs in derby database. This method will insert the ids
 * generated by the repository into the configs passed in itself.
 *
 * Use given prepared statements to create entire config structure in database.
 *
 * @param configurableId//from  w w w  .ja va2  s. co  m
 * @param configs
 * @param type
 * @param baseConfigStmt
 * @param baseInputStmt
 * @param conn
 * @return short number of configs registered.
 * @throws java.sql.SQLException
 */
private short registerConfigs(Long configurableId, Direction direction, List<MConfig> configs, String type,
        PreparedStatement baseConfigStmt, PreparedStatement baseInputStmt, Connection conn)
        throws SQLException {
    short configIndex = 0;

    for (MConfig config : configs) {
        baseConfigStmt.setLong(1, configurableId);

        baseConfigStmt.setString(2, config.getName());
        baseConfigStmt.setString(3, type);
        baseConfigStmt.setShort(4, configIndex++);

        int baseConfigCount = baseConfigStmt.executeUpdate();
        if (baseConfigCount != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0012, Integer.toString(baseConfigCount));
        }
        ResultSet rsetConfigId = baseConfigStmt.getGeneratedKeys();
        if (!rsetConfigId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0013);
        }

        long configId = rsetConfigId.getLong(1);
        config.setPersistenceId(configId);

        if (direction != null) {
            registerConfigDirection(configId, direction, conn);
        }

        // Insert all the inputs
        List<MInput<?>> inputs = config.getInputs();
        registerConfigInputs(config, inputs, baseInputStmt);
        // validate all the input relations
        Map<Long, List<String>> inputRelationships = new HashMap<Long, List<String>>();
        for (MInput<?> input : inputs) {
            List<String> inputOverrides = validateAndGetOverridesAttribute(input, config);
            if (inputOverrides != null && inputOverrides.size() > 0) {
                inputRelationships.put(input.getPersistenceId(), inputOverrides);
            }
        }

        // Insert all input relations
        if (inputRelationships != null && inputRelationships.size() > 0) {
            for (Map.Entry<Long, List<String>> entry : inputRelationships.entrySet()) {
                List<String> children = entry.getValue();
                for (String child : children) {
                    Long childId = config.getInput(child).getPersistenceId();
                    insertConfigInputRelationship(entry.getKey(), childId, conn);
                }
            }
        }
    }
    return configIndex;
}

From source file:org.opoo.oqs.core.AbstractQuery.java

/**
 * ResultSetID/* ww  w. j a  v a2s . c om*/
 *
 * @param sql String
 * @return Serializable
 */
private Serializable getInsertSelectIdentity(String sql) {
    try {
        ConnectionManager manager = queryFactory.getConnectionManager();
        Connection conn = queryFactory.getConnectionManager().getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        try {
            Object values[] = valueArray();
            for (int i = 0; i < values.length; i++) {
                Object value = values[i];
                if (value == null) {
                    Type.SERIALIZABLE.safeSet(ps, value, i + 1);
                } else {
                    TypeFactory.guessType(value).safeSet(ps, value, i + 1);
                }
            }
            if (dialect.supportsInsertSelectIdentity()) {
                if (!ps.execute()) {
                    while (!ps.getMoreResults() && ps.getUpdateCount() != -1) {
                        continue; // Do nothing (but stop checkstyle from complaining).
                    }
                }
                //note early exit!
                ResultSet rs = ps.getResultSet();
                try {
                    return getGeneratedIdentity(rs);
                } finally {
                    //JdbcUtils.closeResultSet(rs);
                    close(rs, null);
                }
            }
            //else if (Settings.isGetGeneratedKeysEnabled())
            //{
            //  ps.executeUpdate();
            //  //note early exit!
            //  return getGeneratedIdentity(ps.getGeneratedKeys());
            //}
            //else
            //{
            //  ps.executeUpdate();
            //need post insert then select identity
            //postInsert.append("NEED");
            //}

            //else if else
            else {
                ps.executeUpdate();
                ResultSet rs = ps.getGeneratedKeys();

                if (rs != null) {
                    //getGeneratedKeys()key
                    try {
                        log.debug("Using getGeneratedKeys() to get keys.");
                        return getGeneratedIdentity(rs);
                    } finally {
                        close(rs, null);
                    }
                }
                //elsegetPostInsertGeneratedIndentity
            }
        } finally {
            //JdbcUtils.closeStatement(ps);
            close(null, ps);
            //JdbcUtils.closeConnection(conn);
            //PostInsertGeneratedIndentiry
            manager.releaseConnection(conn);
        }
    } catch (SQLException ex) {
        //throw new QueryException("could not insert: ", ex);
        log.debug("could not get id for insert, using getPostInsertGeneratedIndentity(): " + ex.getMessage());
    }
    return getPostInsertGeneratedIndentity();
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

private long insertAndGetDriverId(MDriver mDriver, Connection conn) {
    PreparedStatement baseDriverStmt = null;
    try {/*from w w  w  . j  a  v  a 2  s. com*/
        baseDriverStmt = conn.prepareStatement(crudQueries.getStmtInsertIntoConfigurable(),
                Statement.RETURN_GENERATED_KEYS);
        baseDriverStmt.setString(1, mDriver.getUniqueName());
        baseDriverStmt.setString(2, Driver.getClassName());
        baseDriverStmt.setString(3, mDriver.getVersion());
        baseDriverStmt.setString(4, mDriver.getType().name());

        int baseDriverCount = baseDriverStmt.executeUpdate();
        if (baseDriverCount != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(baseDriverCount));
        }

        ResultSet rsetDriverId = baseDriverStmt.getGeneratedKeys();

        if (!rsetDriverId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0010);
        }
        return rsetDriverId.getLong(1);
    } catch (SQLException ex) {
        throw new SqoopException(CommonRepositoryError.COMMON_0044, mDriver.toString(), ex);
    } finally {
        closeStatements(baseDriverStmt);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

private long insertAndGetConnectorId(MConnector mc, Connection conn) {
    PreparedStatement baseConnectorStmt = null;
    try {//ww w . ja v  a  2 s. c om
        baseConnectorStmt = conn.prepareStatement(crudQueries.getStmtInsertIntoConfigurable(),
                Statement.RETURN_GENERATED_KEYS);
        baseConnectorStmt.setString(1, mc.getUniqueName());
        baseConnectorStmt.setString(2, mc.getClassName());
        baseConnectorStmt.setString(3, mc.getVersion());
        baseConnectorStmt.setString(4, mc.getType().name());

        int baseConnectorCount = baseConnectorStmt.executeUpdate();
        if (baseConnectorCount != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(baseConnectorCount));
        }

        ResultSet rsetConnectorId = baseConnectorStmt.getGeneratedKeys();

        if (!rsetConnectorId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0010);
        }
        // connector configurable also have directions
        insertConnectorDirections(rsetConnectorId.getLong(1), mc.getSupportedDirections(), conn);
        return rsetConnectorId.getLong(1);
    } catch (SQLException ex) {
        throw new SqoopException(CommonRepositoryError.COMMON_0011, mc.toString(), ex);
    } finally {
        closeStatements(baseConnectorStmt);
    }
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * {@inheritDoc}/* ww w .  j  av  a 2 s.  c om*/
 */
@Override
public void createLink(MLink link, Connection conn) {
    PreparedStatement stmt = null;
    int result;
    try {
        stmt = conn.prepareStatement(crudQueries.getStmtInsertLink(), Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, link.getName());
        stmt.setLong(2, link.getConnectorId());
        stmt.setBoolean(3, link.getEnabled());
        stmt.setString(4, link.getCreationUser());
        stmt.setTimestamp(5, new Timestamp(link.getCreationDate().getTime()));
        stmt.setString(6, link.getLastUpdateUser());
        stmt.setTimestamp(7, new Timestamp(link.getLastUpdateDate().getTime()));

        result = stmt.executeUpdate();
        if (result != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(result));
        }

        ResultSet rsetConnectionId = stmt.getGeneratedKeys();

        if (!rsetConnectionId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0010);
        }

        long connectionId = rsetConnectionId.getLong(1);

        createInputValues(crudQueries.getStmtInsertLinkInput(), connectionId,
                link.getConnectorLinkConfig().getConfigs(), conn);
        link.setPersistenceId(connectionId);

    } catch (SQLException ex) {
        logException(ex, link);
        throw new SqoopException(CommonRepositoryError.COMMON_0016, ex);
    } finally {
        closeStatements(stmt);
    }
}

From source file:org.osaf.cosmo.migrate.ZeroPointFiveToZeroPointSixMigration.java

private void migrateCalendarCollections(Connection conn, String dialect) throws Exception {
    PreparedStatement stmt = null;
    PreparedStatement insertStampStmt1 = null;
    PreparedStatement insertStampStmt2 = null;
    PreparedStatement insertCalendarStmt = null;
    PreparedStatement deleteAttributeStmt = null;
    PreparedStatement selectAttributeStmt = null;
    PreparedStatement updateCollectionStmt = null;

    ResultSet rs = null;//  w  w w .  j  a  v  a  2 s.  c  o m
    long count = 0;

    log.debug("begin migrateCalendarCollections()");

    try {
        stmt = conn.prepareStatement("select id from item where itemtype=?");
        stmt.setString(1, "calendar");

        insertStampStmt1 = conn
                .prepareStatement("insert into stamp (stamptype, itemid, isactive) values (?,?,1)");
        insertStampStmt1.setString(1, "calendar");
        insertStampStmt2 = conn
                .prepareStatement("insert into stamp (stamptype, itemid, id, isactive) values (?,?,?,1)");
        insertStampStmt2.setString(1, "calendar");

        insertCalendarStmt = conn.prepareStatement(
                "insert into calendar_stamp (stampid, language, description, timezone) values (?,?,?,?)");

        selectAttributeStmt = conn
                .prepareStatement("select stringvalue from attribute where itemid=? and attributename=?");
        updateCollectionStmt = conn.prepareStatement("update item set itemtype=? where itemtype=?");
        updateCollectionStmt.setString(1, "collection");
        updateCollectionStmt.setString(2, "calendar");

        deleteAttributeStmt = conn.prepareStatement(
                "delete from attribute where itemid=? and (attributename=? or attributename=? or attributename=?)");

        deleteAttributeStmt.setString(2, "calendar:description");
        deleteAttributeStmt.setString(3, "calendar:language");
        deleteAttributeStmt.setString(4, "calendar:timezone");

        rs = stmt.executeQuery();

        while (rs.next()) {
            count++;
            long itemId = rs.getLong(1);
            long stampId = 0;

            if ("MySQL5".equals(dialect)) {
                insertStampStmt1.setLong(2, itemId);
                insertStampStmt1.executeUpdate();
            } else {
                stampId = hibernateHelper.getNexIdUsingHiLoGenerator(conn);
                insertStampStmt2.setLong(2, itemId);
                insertStampStmt2.setLong(3, stampId);
                insertStampStmt2.executeUpdate();
            }

            if ("MySQL5".equals(dialect)) {
                ResultSet generatedKeysRs = insertStampStmt1.getGeneratedKeys();
                generatedKeysRs.next();
                stampId = generatedKeysRs.getLong(1);
                generatedKeysRs.close();
            }

            String description = null;
            String timezone = null;
            String language = null;

            selectAttributeStmt.setLong(1, itemId);
            selectAttributeStmt.setString(2, "calendar:description");
            ResultSet attrRs = selectAttributeStmt.executeQuery();
            if (attrRs.next())
                description = attrRs.getString(1);

            attrRs.close();
            selectAttributeStmt.setString(2, "calendar:language");
            attrRs = selectAttributeStmt.executeQuery();
            if (attrRs.next())
                language = attrRs.getString(1);

            attrRs.close();
            selectAttributeStmt.setString(2, "calendar:timezone");
            attrRs = selectAttributeStmt.executeQuery();
            if (attrRs.next())
                timezone = attrRs.getString(1);

            insertCalendarStmt.setLong(1, stampId);

            if (language != null)
                insertCalendarStmt.setString(2, language);
            else
                insertCalendarStmt.setNull(2, Types.VARCHAR);

            if (description != null)
                insertCalendarStmt.setString(3, description);
            else
                insertCalendarStmt.setNull(3, Types.VARCHAR);

            if (timezone != null)
                insertCalendarStmt.setString(4, timezone);
            else
                insertCalendarStmt.setNull(4, Types.CLOB);

            insertCalendarStmt.executeUpdate();

            deleteAttributeStmt.setLong(1, itemId);
            deleteAttributeStmt.executeUpdate();
        }

        updateCollectionStmt.executeUpdate();

    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
        if (insertStampStmt1 != null)
            insertStampStmt1.close();
        if (insertStampStmt2 != null)
            insertStampStmt2.close();
        if (insertCalendarStmt != null)
            insertCalendarStmt.close();
        if (deleteAttributeStmt != null)
            deleteAttributeStmt.close();
        if (selectAttributeStmt != null)
            selectAttributeStmt.close();
        if (updateCollectionStmt != null)
            updateCollectionStmt.close();
    }

    log.debug("processed " + count + " calendars");
}

From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java

/**
 * {@inheritDoc}/*from  w  w  w  . j a  va  2 s .com*/
 */
public void createJob(MJob job, Connection conn) {
    PreparedStatement stmt = null;
    int result;
    try {
        stmt = conn.prepareStatement(crudQueries.getStmtInsertJob(), Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, job.getName());
        stmt.setLong(2, job.getFromLinkId());
        stmt.setLong(3, job.getToLinkId());
        stmt.setBoolean(4, job.getEnabled());
        stmt.setString(5, job.getCreationUser());
        stmt.setTimestamp(6, new Timestamp(job.getCreationDate().getTime()));
        stmt.setString(7, job.getLastUpdateUser());
        stmt.setTimestamp(8, new Timestamp(job.getLastUpdateDate().getTime()));

        result = stmt.executeUpdate();
        if (result != 1) {
            throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(result));
        }

        ResultSet rsetJobId = stmt.getGeneratedKeys();

        if (!rsetJobId.next()) {
            throw new SqoopException(CommonRepositoryError.COMMON_0010);
        }

        long jobId = rsetJobId.getLong(1);

        // from config for the job
        createInputValues(crudQueries.getStmtInsertJobInput(), jobId, job.getFromJobConfig().getConfigs(),
                conn);
        // to config for the job
        createInputValues(crudQueries.getStmtInsertJobInput(), jobId, job.getToJobConfig().getConfigs(), conn);
        // driver config per job
        createInputValues(crudQueries.getStmtInsertJobInput(), jobId, job.getDriverConfig().getConfigs(), conn);

        job.setPersistenceId(jobId);

    } catch (SQLException ex) {
        logException(ex, job);
        throw new SqoopException(CommonRepositoryError.COMMON_0023, ex);
    } finally {
        closeStatements(stmt);
    }
}

From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java

/**
 * Register player/* w  w  w . java 2  s  . c o m*/
 *
 * @param encryptedPassword player's encrypted password
 * @return a LoginResponse to send the CommandSender ("LOGIN_WENT_ASYNCHRONOUS_SUCCESSFULLY" is a success)
 * @see Util#encryptString(String) for password encrypting
 */
public OnlinePlayer.LoginResponse registerPlayer(@NotNull final OnlinePlayer onlinePlayer,
        @NotNull final String encryptedPassword) {
    final OfflinePlayer offlinePlayer = onlinePlayer.getOfflinePlayer();
    // Check if player is registered
    if (offlinePlayer.isRegistered())
        return OnlinePlayer.LoginResponse.ALREADY_REGISTERED;

    Bukkit.getScheduler().runTaskAsynchronously(LobsterCraft.plugin, () -> {
        try {
            // Set offline player's attributes (lastIp is just set on login)
            offlinePlayer.lastIp = onlinePlayer.getPlayer().getAddress().getAddress().getHostAddress();
            offlinePlayer.encryptedPassword = encryptedPassword;
            offlinePlayer.databaseState = DatabaseState.INSERT_TO_DATABASE;

            // Register player on database
            Connection connection = LobsterCraft.dataSource.getConnection();

            // Prepare statement
            PreparedStatement preparedStatement = connection
                    .prepareStatement("INSERT INTO `minecraft`.`user_profiles`"
                            + "(`playerName`, `password`, `moneyAmount`, `city_cityId`, `cityOccupation`, `lastTimeOnline`, `timePlayed`, `lastIp`)"
                            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS);

            // Set variables
            preparedStatement.setString(1, offlinePlayer.getPlayerName().toLowerCase()); // Lower case it just to make sure
            preparedStatement.setString(2, offlinePlayer.getEncryptedPassword());
            preparedStatement.setDouble(3, offlinePlayer.getMoneyAmount());
            preparedStatement.setObject(4, offlinePlayer.getCityId(), Types.SMALLINT); // Will write null if is null
            preparedStatement.setObject(5,
                    offlinePlayer.getCityOccupation() != null
                            ? offlinePlayer.getCityOccupation().getOccupationId()
                            : null,
                    Types.TINYINT);
            preparedStatement.setLong(6, offlinePlayer.getLastTimeOnline());
            preparedStatement.setLong(7, offlinePlayer.getTimePlayed());
            preparedStatement.setString(8, offlinePlayer.getLastIp());

            // Execute statement
            preparedStatement.execute();

            // Retrieve generated keys
            ResultSet generatedKeys = preparedStatement.getGeneratedKeys();

            // Check if key exists
            if (!generatedKeys.next())
                throw new SQLException("Query didn't return any generated key");

            offlinePlayer.playerId = generatedKeys.getInt("playerId");

            // Close everything
            generatedKeys.close();
            preparedStatement.close();
            connection.close();

            // Check if was successful
            if (offlinePlayer.getPlayerId() == null || offlinePlayer.getPlayerId() <= 0)
                throw new IllegalStateException(Util.appendStrings("Failed to register player: playerId is ",
                        offlinePlayer.getPlayerId()));

            // Change player's instance location
            synchronized (playerMapsLock) {
                unregisteredOfflinePlayers_name.remove(offlinePlayer.getPlayerName(), offlinePlayer);
                registeredOfflinePlayers_name.put(offlinePlayer.getPlayerName(), offlinePlayer);
                registeredOfflinePlayers_id.put(offlinePlayer.getPlayerId(), offlinePlayer);

                // Check if player has a city (even though he just registered...)
                if (offlinePlayer.getCityId() != null) {
                    if (!registeredOfflinePlayers_cityId.containsKey(offlinePlayer.getCityId()))
                        registeredOfflinePlayers_cityId.put(offlinePlayer.getCityId(), new HashSet<>());
                    registeredOfflinePlayers_cityId.get(offlinePlayer.getCityId()).add(offlinePlayer);
                }
            }

            // Update database state
            offlinePlayer.databaseState = DatabaseState.ON_DATABASE;
            onlinePlayer.onlineState = OnlinePlayer.OnlineState.PRE_LOGIN;

            // Force login
            forceLoginPlayer(onlinePlayer);
        } catch (Exception exception) {
            exception.printStackTrace();
            onlinePlayer.getPlayer().kickPlayer("4Um erro ocorreu ao registrar!");
        }
    });

    return OnlinePlayer.LoginResponse.LOGIN_WENT_ASYNCHRONOUS_SUCCESSFULLY;
}