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.geowebcache.storage.jdbc.metastore.JDBCMBIdCache.java

/**
 * Ask the database for next auto increment
 * /*  w w w.  ja v a 2 s.co m*/
 * @throws SQLException
 */
private Long doInsert(String table, String key) throws SQLException {
    Long res = null;

    final Connection connection = wrpr.getConnection();
    PreparedStatement prep = null;
    ResultSet rs = null;
    try {
        String query = "INSERT INTO " + table + " (value) VALUES (?)";

        prep = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

        prep.setString(1, key);

        prep.executeUpdate();

        rs = prep.getGeneratedKeys();
        rs.first();
        res = Long.valueOf(rs.getLong(1));
    } catch (SQLException se) {
        log.error(se.getMessage());
    } finally {
        close(rs);
        close(prep);
        close(connection);
    }

    return res;
}

From source file:net.mindengine.oculus.frontend.service.project.build.JdbcBuildDAO.java

@Override
public long createBuild(Build build) throws Exception {
    String sql = "insert into builds (name, description, date, project_id) values (?,?,?,?)";
    PreparedStatement ps = getConnection().prepareStatement(sql);
    ps.setString(1, build.getName());//from ww w  .  j  a v a 2s  .  c om
    ps.setString(2, build.getDescription());
    ps.setTimestamp(3, new Timestamp(build.getDate().getTime()));
    ps.setLong(4, build.getProjectId());

    logger.info(ps);
    ps.execute();

    ResultSet rs = ps.getGeneratedKeys();
    if (rs.next()) {
        return rs.getLong(1);
    }
    return 0;
}

From source file:storybook.model.oldModel.ModelMigration.java

public int getGeneratedId(PreparedStatement stmt) throws SQLException {
    int retour = -1;
    ResultSet rs = null;/*from   w  w  w .jav  a  2s  . c  om*/
    try {
        rs = stmt.getGeneratedKeys();
        int count = 0;
        while (rs.next()) {
            if (count > 0) {
                throw new SQLException("error: got more than one id");
            }
            retour = rs.getInt(1);
            ++count;
        }
    } catch (SQLException exc) {
        SbApp.error("*** ModelMigration.getGeneratedId(" + stmt.toString() + ")", exc);
    } finally {
        this.closeResultSet(rs);
    }
    return retour;
}

From source file:ca.fastenalcompany.servlet.ProductServlet.java

public int update(String query, String... params) {
    Connection conn = null;//from   w  w w.j  a va  2s . c  o  m
    int result = -1;
    try {
        conn = DBManager.getMysqlConn();
        PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        for (int i = 1; i <= params.length; i++) {
            pstmt.setString(i, params[i - 1]);
        }
        System.out.println(query);
        int rowsEffected = pstmt.executeUpdate();
        ResultSet rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            result = rs.getInt(1);
        } else if (rowsEffected > 0) {
            result = Integer.parseInt(params[params.length - 1]);
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            System.out.println("DB connection closed");
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:opengovcrawler.DB.java

/**
 * Insert consultations into DB./*from   w  w w .  jav  a2 s.c o  m*/
 *
 * @param currentCons - The consultation to be inserted
 * @param orgId - the ministry id that the consultation belongs to
 * @param numOfArticles - The number of articles of the current consultation
 * @return - The database ID for the inserted consultation
 * @throws java.sql.SQLException
 */
public static int InsertNewConsultation(Consultation currentCons, int orgId, int numOfArticles)
        throws SQLException {
    Timestamp startDate = null;
    Timestamp endDate = null;
    try {
        // Convert Strings to Datetimes
        startDate = ConvertDateMonth(currentCons.startDate);
        endDate = ConvertDateMonth(currentCons.endDate);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    String insertConsultationSql = "INSERT INTO consultation"
            + "(start_date, end_date, title, short_description, organization_id, consultation_url, completed, completed_text, report_text, report_url, num_of_articles) VALUES"
            + "(?,?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement preparedStatement = connection.prepareStatement(insertConsultationSql,
            PreparedStatement.RETURN_GENERATED_KEYS);
    preparedStatement.setTimestamp(1, startDate);
    preparedStatement.setTimestamp(2, endDate);
    preparedStatement.setString(3, currentCons.title);
    preparedStatement.setString(4, currentCons.bodyText);
    preparedStatement.setInt(5, orgId);
    preparedStatement.setString(6, currentCons.url);
    preparedStatement.setInt(7, 0);
    preparedStatement.setString(8, currentCons.completed_text);
    preparedStatement.setString(9, currentCons.report_text);
    preparedStatement.setString(10, currentCons.report_url);
    preparedStatement.setInt(11, numOfArticles);
    preparedStatement.executeUpdate();
    ResultSet rs = preparedStatement.getGeneratedKeys();
    int conIdAfterIns = -1;
    if (rs.next()) {
        conIdAfterIns = rs.getInt(1);
    }
    preparedStatement.close();
    return conIdAfterIns;
}

From source file:org.wso2.carbon.social.adaptor.DefaultQueryAdaptor.java

@Override
public long insertCommentActivity(Connection connection, String json, String targetId, String userId,
        String tenantDomain, int totalLikes, int totalUnlikes, int timeStamp) throws SQLException {

    PreparedStatement commentStatement;

    try {/* www . j a  v  a2  s .co  m*/
        commentStatement = getInsertCommentActivityPreparedStatement(connection, json, targetId, userId,
                tenantDomain, totalLikes, totalUnlikes, timeStamp);
        commentStatement.executeUpdate();

        ResultSet generatedKeys = commentStatement.getGeneratedKeys();

        return getGenaratedKeys(generatedKeys);

    } catch (SQLException e) {
        log.error("Error while publishing comment activity. ", e);
        throw e;
    }
}

From source file:at.becast.youploader.account.Account.java

public int save() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    LOG.info("Saving account");
    try {/*from  w  w  w.j  a v a2  s .  c om*/
        PreparedStatement stmt = c
                .prepareStatement("INSERT INTO `accounts` (`name`,`refresh_token`,`cookie`) VALUES(?,?,?)");
        stmt.setString(1, this.name);
        stmt.setString(2, this.refreshToken);
        stmt.setString(3, mapper.writeValueAsString(this.cdata));
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        stmt.close();
        if (rs.next()) {
            int id = rs.getInt(1);
            rs.close();
            LOG.info("Account saved");
            return id;
        } else {
            LOG.error("Could not save account {}!", this.name);
            return -1;
        }
    } catch (SQLException e) {
        LOG.error("Could not save account Ex:", e);
        return -1;
    }
}

From source file:org.wso2.carbon.social.db.adapter.GenericQueryAdapter.java

@Override
public long insertCommentActivity(Connection connection, String json, String targetId, String userId,
        String tenantDomain, int totalLikes, int totalUnlikes, int timeStamp) throws SQLException {

    PreparedStatement commentStatement;

    try {//w w  w.j a  v  a2  s  . c o  m
        commentStatement = getInsertCommentActivityPreparedStatement(connection, json, targetId, userId,
                tenantDomain, totalLikes, totalUnlikes, timeStamp);
        commentStatement.executeUpdate();

        ResultSet generatedKeys = commentStatement.getGeneratedKeys();

        return getGenaratedKeys(generatedKeys);

    } catch (SQLException e) {
        log.error("Error while publishing comment activity. " + e.getMessage(), e);
        throw e;
    }
}

From source file:oobbit.orm.Users.java

/**
 * Creates a user and returns its id.//from ww  w .j av a  2 s.  c  o  m
 *
 * @param username Username for the user
 * @param email    Email for the user
 * @param password Hashed password
 *
 * @return ID of the registered user
 *
 * @throws SQLException
 */
public int registerNewUser(String username, String email, String password) throws SQLException {
    PreparedStatement statement = getConnection().prepareStatement(
            "INSERT INTO `oobbit`.`users` (`user_id`, `username`, `email`, `password`, `access_level`, `create_time`) VALUES (NULL, ?, ?, ?, '1', CURRENT_TIMESTAMP);",
            Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, username);
    statement.setString(2, email);
    statement.setString(3, hash(password));

    statement.executeUpdate();
    ResultSet rs = statement.getGeneratedKeys();
    if (rs.next()) {
        return rs.getInt(1);
    }

    throw new SQLException("Could not add user!");
}

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

public Long create(IQuestNode answer, Connection conn) throws IOException, SQLException {
    Long result = null;// ww w  .j a v  a2 s . c  o  m
    String query = getCreateAnswerQuery();
    PreparedStatement st = null;
    try {
        st = conn.prepareStatement(query, new String[] { "id" });
        st.setString(1, answer.getNode());
        st.setInt(2, answer.getNumb());
        st.setLong(3, answer.getUserId());
        st.setInt(4, answer.getType());
        st.setInt(5, answer.getGol());
        st.setLong(6, answer.getHead());
        st.executeUpdate();
        ResultSet idRs = st.getGeneratedKeys();
        if (idRs.next()) {
            result = idRs.getLong(1);
        }
    } finally {
        readFinally(null, st);
    }
    return result;
}