Example usage for java.sql Statement RETURN_GENERATED_KEYS

List of usage examples for java.sql Statement RETURN_GENERATED_KEYS

Introduction

In this page you can find the example usage for java.sql Statement RETURN_GENERATED_KEYS.

Prototype

int RETURN_GENERATED_KEYS

To view the source code for java.sql Statement RETURN_GENERATED_KEYS.

Click Source Link

Document

The constant indicating that generated keys should be made available for retrieval.

Usage

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

public static Integer addRecord(final Connection conn, final String sql, final Object... parameters)
        throws SQLException {
    final PreparedStatement stmt = StatementFormat.prepare(conn, Statement.RETURN_GENERATED_KEYS, sql,
            parameters);//from   w  ww .  ja v  a  2  s.co m
    try {
        if (stmt.executeUpdate() != 1) {
            if (log.isErrorEnabled())
                log.error("failed to add record");
            return null;
        }
        final ResultSet rsKey = stmt.getGeneratedKeys();
        try {
            rsKey.next();
            return rsKey.getInt(1);
        } finally {
            rsKey.close();
        }
    } finally {
        stmt.close();
    }
}

From source file:org.biblionum.authentification.modele.UtilisateurModele.java

/**
 * Java method that inserts a row in the generated sql table and returns the
 * new generated id/*  w ww  .  j  a  va2 s.  c o m*/
 *
 * @param con (open java.sql.Connection)
 * @param nom
 * @param password
 * @param pseudo
 * @param prenom
 * @param utilisateur_type_id
 * @return id (database row id [id])
 * @throws SQLException
 */
public int insertIntoUtilisateur(DataSource ds, String nom, String password, String pseudo, String prenom)
        throws SQLException {
    con = ds.getConnection();
    int generatedId = -1;
    String sql = "INSERT INTO utilisateur (nom, " + "password, pseudo, prenom)" + "VALUES (?, ?, ?, ?)";
    PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, nom);
    statement.setString(2, password);
    statement.setString(3, pseudo);
    statement.setString(4, prenom);

    statement.execute();
    ResultSet auto = statement.getGeneratedKeys();

    if (auto.next()) {
        generatedId = auto.getInt(1);
    } else {
        generatedId = -1;
    }

    statement.close();
    con.close();
    return generatedId;
}

From source file:org.mskcc.cbio.cgds.dao.DaoGistic.java

public static void addGistic(Gistic gistic) throws DaoException, validationException {
    if (gistic == null) {
        throw new DaoException("Given a null gistic object");
    }/*from  w  w w  .  j a v a  2  s .c  om*/

    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    ValidateGistic.validateBean(gistic);

    try {
        con = JdbcUtil.getDbConnection(DaoGistic.class);
        // insert into SQL gistic table
        pstmt = con.prepareStatement("INSERT INTO gistic (`CANCER_STUDY_ID`," + "`CHROMOSOME`, "
                + "`CYTOBAND`, " + "`WIDE_PEAK_START`, " + "`WIDE_PEAK_END`, " + "`Q_VALUE`, " + "`AMP`) "
                + "VALUES (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);

        pstmt.setInt(1, gistic.getCancerStudyId());
        pstmt.setInt(2, gistic.getChromosome());
        pstmt.setString(3, gistic.getCytoband());
        pstmt.setInt(4, gistic.getPeakStart());
        pstmt.setInt(5, gistic.getPeakEnd());
        pstmt.setDouble(6, gistic.getqValue());
        pstmt.setBoolean(7, gistic.getAmp());
        pstmt.executeUpdate();

        // insert into SQL gistic_to_gene table
        rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            int autoId = rs.getInt(1);
            gistic.setInternalId(autoId);
        }
        addGisticGenes(gistic, con);

    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JdbcUtil.closeAll(DaoGistic.class, con, pstmt, rs);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dao.users.PgUserGroupPersistenceManager.java

@Override
public UserGroup createGroup(final UserGroup group) throws SegueDatabaseException {
    try (Connection conn = database.getDatabaseConnection()) {
        PreparedStatement pst;//from  ww w .j  av a  2s.  c  o m
        pst = conn.prepareStatement("INSERT INTO groups(group_name, owner_id, created)" + " VALUES (?, ?, ?);",
                Statement.RETURN_GENERATED_KEYS);
        pst.setString(1, group.getGroupName());
        pst.setLong(2, group.getOwnerId());

        if (group.getCreated() != null) {
            pst.setTimestamp(3, new Timestamp(group.getCreated().getTime()));
        } else {
            pst.setTimestamp(3, new Timestamp(new Date().getTime()));
        }

        if (pst.executeUpdate() == 0) {
            throw new SegueDatabaseException("Unable to save group.");
        }

        try (ResultSet generatedKeys = pst.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                Long id = generatedKeys.getLong(1);
                group.setId(id);

            } else {
                throw new SQLException("Creating group failed, no ID obtained.");
            }
        }

        return group;

    } catch (SQLException e) {
        throw new SegueDatabaseException("Postgres exception", e);
    }
}

From source file:org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.NotificationDAOImpl.java

@Override
public int addNotification(int deviceId, int tenantId, Notification notification)
        throws NotificationManagementException {
    Connection conn;/*from   w  w  w. j  a va  2 s.co  m*/
    PreparedStatement stmt = null;
    ResultSet rs;
    int notificationId = -1;
    try {
        conn = NotificationManagementDAOFactory.getConnection();
        String sql = "INSERT INTO DM_NOTIFICATION(DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION, TENANT_ID) "
                + "VALUES (?, ?, ?, ?, ?)";
        stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setInt(1, deviceId);
        stmt.setInt(2, notification.getOperationId());
        stmt.setString(3, notification.getStatus().toString());
        stmt.setString(4, notification.getDescription());
        stmt.setInt(5, tenantId);
        stmt.execute();
        rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            notificationId = rs.getInt(1);
        }
    } catch (Exception e) {
        throw new NotificationManagementException(
                "Error occurred while adding the " + "Notification for device id : " + deviceId, e);
    } finally {
        NotificationDAOUtil.cleanupResources(stmt, null);
    }
    return notificationId;
}

From source file:org.dcache.chimera.H2FsSqlDriver.java

@Override
Stat createInode(String id, int type, int uid, int gid, int mode, int nlink, long size) {
    /* H2 uses weird names for the column with the auto-generated key, so we cannot use the code
     * in the base class.//from   w  w w  .  ja v  a 2  s. c  o m
     */
    Timestamp now = new Timestamp(System.currentTimeMillis());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    _jdbc.update(con -> {
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO t_inodes (ipnfsid,itype,imode,inlink,iuid,igid,isize,iio,"
                        + "ictime,iatime,imtime,icrtime,igeneration) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, id);
        ps.setInt(2, type);
        ps.setInt(3, mode & UnixPermission.S_PERMS);
        ps.setInt(4, nlink);
        ps.setInt(5, uid);
        ps.setInt(6, gid);
        ps.setLong(7, size);
        ps.setInt(8, _ioMode);
        ps.setTimestamp(9, now);
        ps.setTimestamp(10, now);
        ps.setTimestamp(11, now);
        ps.setTimestamp(12, now);
        ps.setLong(13, 0);
        return ps;
    }, keyHolder);

    Stat stat = new Stat();
    stat.setIno((Long) keyHolder.getKey());
    stat.setId(id);
    stat.setCrTime(now.getTime());
    stat.setGeneration(0);
    stat.setSize(size);
    stat.setATime(now.getTime());
    stat.setCTime(now.getTime());
    stat.setMTime(now.getTime());
    stat.setUid(uid);
    stat.setGid(gid);
    stat.setMode(mode & UnixPermission.S_PERMS | type);
    stat.setNlink(nlink);
    stat.setDev(17);
    stat.setRdev(13);

    return stat;
}

From source file:com.wso2telco.dep.mediator.dao.ProvisionDAO.java

public Integer provisionServiceEntry(String notifyURL, String serviceProvider) throws SQLException, Exception {

    Connection con = null;/*from   w  ww  .  j  a v  a 2 s . co  m*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer newId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        if (con == null) {

            throw new Exception("Connection not found");
        }

        StringBuilder insertQueryString = new StringBuilder("INSERT INTO ");
        insertQueryString.append(DatabaseTables.PROVISION_SERVICE_ENTRY.getTableName());
        insertQueryString.append(" (notifyurl, service_provider, is_active) ");
        insertQueryString.append("VALUES (?, ?, ?)");

        ps = con.prepareStatement(insertQueryString.toString(), Statement.RETURN_GENERATED_KEYS);

        ps.setString(1, notifyURL);
        ps.setString(2, serviceProvider);
        ps.setInt(3, 0);

        log.debug("sql query in provisionServiceEntry : " + ps);

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            newId = rs.getInt(1);
        }
    } catch (SQLException e) {

        log.error("database operation error in provisionServiceEntry : ", e);
        throw e;
    } catch (Exception e) {

        log.error("error in provisionServiceEntry : ", e);
        throw e;
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return newId;
}

From source file:org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.OperationDAOImpl.java

public int addOperation(Operation operation) throws OperationManagementDAOException {
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from w ww  . j  av a  2  s.c  om*/
    try {
        Connection connection = OperationManagementDAOFactory.getConnection();
        String sql = "INSERT INTO DM_OPERATION(TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE)  "
                + "VALUES (?, ?, ?, ?)";
        stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, operation.getType().toString());
        stmt.setTimestamp(2, new Timestamp(new Date().getTime()));
        stmt.setTimestamp(3, null);
        stmt.setString(4, operation.getCode());
        stmt.executeUpdate();

        rs = stmt.getGeneratedKeys();
        int id = -1;
        if (rs.next()) {
            id = rs.getInt(1);
        }
        return id;
    } catch (SQLException e) {
        throw new OperationManagementDAOException("Error occurred while adding operation metadata", e);
    } finally {
        OperationManagementDAOUtil.cleanupResources(stmt, rs);
    }
}

From source file:org.tec.webapp.jdbc.entity.impl.UserDbaImpl.java

/** {@inheritDoc} */
public Long insert(UserBean user) throws DataAccessException {
    ParameterMap params = getParams(user);

    PreparedStatementCreator creator = PreparedStatementBuilder.getInsertBuilder(TABLE, params,
            Statement.RETURN_GENERATED_KEYS);

    return insert(creator);
}

From source file:iddb.runtime.db.model.dao.impl.mysql.UserDAOImpl.java

@Override
public void save(User user) {
    String sql;// w  w w .j  ava  2 s.  c  om
    if (user.getKey() == null) {
        sql = "insert into user (loginid, roles, updated, created, password) values (?,?,?,?,?)";
    } else {
        sql = "update user set loginid = ?," + "roles = ?," + "updated = ? where id = ? limit 1";
    }
    Connection conn = null;
    try {
        conn = ConnectionFactory.getMasterConnection();
        PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, user.getLoginId());
        st.setString(2, Functions.join(user.getRoles(), ","));
        st.setTimestamp(3, new Timestamp(new Date().getTime()));
        if (user.getKey() != null) {
            st.setLong(4, user.getKey());
        } else {
            st.setTimestamp(4, new Timestamp(new Date().getTime()));
            st.setString(5, user.getPassword());
        }
        st.executeUpdate();
        if (user.getKey() == null) {
            ResultSet rs = st.getGeneratedKeys();
            if (rs != null && rs.next()) {
                user.setKey(rs.getLong(1));
            } else {
                logger.warn("Couldn't get id for user {}", user.getLoginId());
            }
        }
    } catch (SQLException e) {
        logger.error("Save: {}", e);
    } catch (IOException e) {
        logger.error("Save: {}", e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}