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:org.mifos.framework.persistence.Upgrade.java

@SuppressWarnings("PMD.CloseResource")
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = {
        "OBL_UNSATISFIED_OBLIGATION" }, justification = "The statement is closed.")
protected int addLookupEntity(Connection connection, String name, String description) throws SQLException {
    int newId = -1;
    PreparedStatement statement = connection.prepareStatement(
            "insert into lookup_entity(entity_id,entity_name,description) values(null,?,?)",
            PreparedStatement.RETURN_GENERATED_KEYS);
    statement.setString(1, name);// ww  w. ja  va 2s  .c  o  m
    statement.setString(2, description);
    statement.executeUpdate();
    ResultSet keys = statement.getGeneratedKeys();
    keys.next();
    newId = Integer.parseInt(keys.getString(1));
    statement.close();
    return newId;
}

From source file:org.stanwood.media.database.sdb.AbstractGenericDatabase.java

/**
 * This is used to execute an update statement that takes parameters. The SQL should
 * contain ? were the parameters should be inserted.
 *
 * @param connection   a connection to be re-used, useful for running a series of updates as a
 *                   transaction//w ww .  j a va 2  s.c  o  m
 * @param sql         The SQL to execute on the database
 * @param params      the parameters to insert into the SQL statement, replacing ?.
 * @return             if a key was generated, then it is returned, otherwise -1
 * @throws SQLException Thrown if their is a problem talking to the database
 */
@Override
public long executeUpdate(Connection connection, String sql, Object[] params) throws SQLException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        //Prepare and execute the update
        stmt = getStatement(connection, sql, params);
        stmt.executeUpdate();

        //Check for any keys
        rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            long key = rs.getLong(1);
            return key;
        }

        //If not return
        return -1;

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        closeDatabaseResources(null, stmt, rs);
    }
}

From source file:org.forumj.dbextreme.db.dao.FJFolderDao.java

public Long create(String folderName, IUser user) throws SQLException, ConfigurationException, IOException {
    Long result = null;/* w  w  w.ja v  a2  s  .  c  o m*/
    String query = getCreateFolderQuery();
    PreparedStatement st = null;
    Connection conn = null;
    boolean error = true;
    try {
        conn = getConnection();
        conn.setAutoCommit(false);
        st = conn.prepareStatement(query, new String[] { "id" });
        st.setString(1, folderName);
        st.setLong(2, user.getId());
        st.executeUpdate();
        ResultSet idRs = st.getGeneratedKeys();
        if (idRs.next()) {
            result = idRs.getLong(1);
        }
        FJInterfaceDao interfaceDao = new FJInterfaceDao();
        //TODO Magic integer!
        interfaceDao.addFolder(3, result, user, conn);
        interfaceDao.addFolder(4, result, user, conn);
        error = false;
    } finally {
        writeFinally(conn, st, error);
    }
    return result;
}

From source file:org.stanwood.media.database.sdb.AbstractGenericDatabase.java

/**
 * This is used to insert table row into a table. The table row is made up from fields.
 * @param connection a connection to be re-used, useful for running a series
 * @param tableName  The name of the table
 * @param fields     The fields of the table that are to be inserted.
 * @return If a key was generated, then it is pass here, otherwise -1
 * @throws SQLException Thrown if their is a problem talking to the database
 *//*  w w w.  ja  v a  2s  . co  m*/
@Override
public long insertIntoTable(Connection connection, String tableName, List<Field> fields) throws SQLException {
    StringBuilder sql = new StringBuilder();
    sql.append("INSERT INTO `" + tableName + "` ("); //$NON-NLS-1$ //$NON-NLS-2$
    boolean first = true;
    for (Field field : fields) {
        if (!first) {
            sql.append(","); //$NON-NLS-1$
        }
        sql.append("`"); //$NON-NLS-1$
        sql.append(field.getKey());
        sql.append("`"); //$NON-NLS-1$
        first = false;
    }
    sql.append(") VALUES ("); //$NON-NLS-1$
    Object params[] = new Object[fields.size()];
    for (int i = 0; i < fields.size(); i++) {
        if (i == 0) {
            sql.append("?"); //$NON-NLS-1$
        } else {
            sql.append(",?"); //$NON-NLS-1$
        }
        params[i] = fields.get(i).getValue();
    }
    sql.append(")"); //$NON-NLS-1$

    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        //Prepare and execute the update
        stmt = getStatement(connection, sql.toString(), params);
        stmt.executeUpdate();

        //Check for any keys
        rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            long key = rs.getLong(1);
            return key;
        }

        //If not return
        return -1;

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw e;
    } finally {
        closeDatabaseResources(null, stmt, rs);
    }
}

From source file:org.primeframework.persistence.jdbc.Insert.java

/**
 * Performs the insert.//w  ww . ja  va  2 s  .  c  o m
 *
 * @param handler The generated keys handler.
 * @return The result.
 * @throws InsertException If the insert fails.
 */
public <T> InsertResult<T> go(GeneratedKeyHandler<T> handler) throws InsertException {
    PreparedStatement ps = null;
    try {
        ps = c.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
        setParams(ps);

        int results = ps.executeUpdate();
        if (results != 1) {
            throw new InsertException("Inserting a single row failed completely");
        }

        ResultSet keysRS = ps.getGeneratedKeys();
        List<T> keys = new ArrayList<T>();
        while (keysRS.next()) {
            keys.add(handler.handle(keysRS));
        }

        return new InsertResult<T>(results, keys);
    } catch (SQLException e) {
        throw new InsertException(e);
    } finally {
        close(ps);
    }
}

From source file:data.AbstractRepository.java

/**
*
* @param t//  www.  j  av a2s  .  c om
* @throws DataException
*/
@Override
public void save(T t) throws DataException {
    String query;
    int generatedKeys;

    if (t.getId() < 0) {
        query = getInsertQuery(t);
        generatedKeys = Statement.RETURN_GENERATED_KEYS;
    } else {
        query = getUpdateQuery(t);
        generatedKeys = Statement.NO_GENERATED_KEYS;
    }

    Connection connection;
    PreparedStatement statement;
    try {
        connection = DriverManager.getConnection(url, username, password);
        statement = connection.prepareStatement(query, generatedKeys);
        statement.executeUpdate();

        if (t.getId() > 0)
            return;

        ResultSet keys = statement.getGeneratedKeys();

        try {

            if (keys.next()) {
                t.setId(keys.getInt(1));
            }
        } finally {
            keys.close();
            statement.close();
            connection.close();
        }
    } catch (SQLException ex) {
        throw new DataException("Error saving: " + t);
    }
}

From source file:Classes.Database.java

/**
 * Makes a save SQL statement and executes it
 *
 * @param sql       The query, use an "?" at the place of a input. Like this:
 *                  INSERT INTO TABLE('name', 'lastname' , enz ) VALUES(?,?, enz);
 * @param arguments The arguments correspont to same questionmark.
 * @return The generated key//  ww w. j  a  v a  2s .c o m
 * @throws SQLException
 */
public Integer setDatabase(String sql, Object... arguments) {
    Connection conn = null;
    PreparedStatement psta = null;
    ResultSet rs = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url, username, password);
        psta = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        EscapeSQL(psta, arguments);

        psta.executeUpdate();
        rs = psta.getGeneratedKeys();
        if (rs != null && rs.next()) {
            if (rs.getInt(1) == 0) { //maybe errors
                return -1;
            }
            return rs.getInt(1);
        }
        return -1;
    } catch (SQLException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "SQL Error: " + e.getMessage(), e);
        return -1;
    } catch (ClassNotFoundException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "Class Error " + e.getMessage(), e);
        return -1;
    } finally {
        if (conn != null) {
            //close and commit
            Logger.getAnonymousLogger().log(Level.INFO, "Commit" + sql);
            try {
                conn.commit();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
            try {
                conn.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }

        if (psta != null) {
            try {
                psta.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                Logger.getAnonymousLogger().log(Level.WARNING, e.getMessage(), e);
            }
        }
    }
}

From source file:com.enigmastation.ml.perceptron.impl.HSQLDBPerceptronRepository.java

private int createNode(Object token, Layer layer) {
    int id;/*from   w ww.  ja  v a  2s  .c  om*/
    PreparedStatement ps;
    ResultSet rs;
    try (Connection conn = getConnection()) {
        ps = conn.prepareStatement("insert into node (create_key, layer) values (?, ?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, token.toString());
        ps.setInt(2, layer.ordinal());
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        id = rs.getInt(1);
        rs.close();
        ps.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return id;
}

From source file:net.mindengine.oculus.frontend.service.customization.JdbcCustomizationDAO.java

@Override
public long saveUnitCustomizationValue(UnitCustomizationValue unitCustomizationValue) throws Exception {
    UnitCustomizationValue value = null;

    if (unitCustomizationValue.getId() == null || unitCustomizationValue.getId() < 1) {
        value = getUnitCustomizationValue(unitCustomizationValue.getCustomizationId(),
                unitCustomizationValue.getUnitId());
    } else//from w w  w .  ja  v a  2s  .  c o m
        value = unitCustomizationValue;

    if (value == null) {
        PreparedStatement ps = getConnection().prepareStatement(
                "insert into unit_customization_values (unit_id, customization_id, value) values (?,?,?)");
        ps.setLong(1, unitCustomizationValue.getUnitId());
        ps.setLong(2, unitCustomizationValue.getCustomizationId());
        ps.setString(3, unitCustomizationValue.getValue());

        logger.info(ps);
        ps.execute();
        ResultSet rs = ps.getGeneratedKeys();
        if (rs.next()) {
            return rs.getLong(1);
        }
    } else {
        update("update unit_customization_values set value = :value where id = :id", "value",
                unitCustomizationValue.getValue(), "id", value.getId());

        return value.getId();
    }
    return 0;
}

From source file:org.wso2.carbon.device.mgt.mobile.dao.impl.MobileOperationDAOImpl.java

@Override
public int addMobileOperation(MobileOperation mblOperation) throws MobileDeviceManagementDAOException {
    int status = -1;
    Connection conn = null;// w w w.  jav  a  2  s  .c  o  m
    PreparedStatement stmt = null;
    try {
        conn = this.getConnection();
        String createDBQuery = "INSERT INTO AD_OPERATION(FEATURE_CODE, CREATED_DATE) VALUES ( ?, ?)";
        stmt = conn.prepareStatement(createDBQuery, new String[] { COLUMN_OPERATION_ID });
        stmt.setString(1, mblOperation.getFeatureCode());
        stmt.setLong(2, mblOperation.getCreatedDate());
        int rows = stmt.executeUpdate();
        if (rows > 0) {
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs != null && rs.next()) {
                status = rs.getInt(1);
            }
            if (log.isDebugEnabled()) {
                log.debug("Added a new MobileOperation " + mblOperation.getFeatureCode() + " to MDM database.");
            }
        }
    } catch (SQLException e) {
        String msg = "Error occurred while adding the operation - '" + mblOperation.getFeatureCode()
                + "' to MBL_OPERATION table";
        log.error(msg, e);
        throw new MobileDeviceManagementDAOException(msg, e);
    } finally {
        MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null);
    }
    return status;
}