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:AutoGenKeys.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con = null;//from   w w w .  j  a v a 2 s . c  o  m
    PreparedStatement pstmt;
    String insert = "INSERT INTO COFFEES VALUES ('HYPER_BLEND', " + "101, 10.99, 0, 0)";
    String update = "UPDATE COFFEES SET PRICE = ? WHERE KEY = ?";

    try {

        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        pstmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);

        pstmt.executeUpdate();
        ResultSet keys = pstmt.getGeneratedKeys();

        int count = 0;

        keys.next();
        int key = keys.getInt(1);

        pstmt = con.prepareStatement(update);
        pstmt.setFloat(1, 11.99f);
        pstmt.setInt(2, key);
        pstmt.executeUpdate();

        keys.close();
        pstmt.close();
        con.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:org.forumj.dbextreme.db.service.test.voice.tests.ReadVoiceTest.java

private static void executeSql(PreparedStatement st, IFJVoice voice) throws SQLException {
    st.executeUpdate();//w  w  w  .  j  a v a2  s  .c  o m
    ResultSet idRs = st.getGeneratedKeys();
    if (idRs.next()) {
        voice.setId(idRs.getLong(1));
    }
}

From source file:Main.java

public static long writeJavaObject(Connection conn, Object object) throws Exception {
    String className = object.getClass().getName();
    PreparedStatement pstmt = conn.prepareStatement(WRITE_OBJECT_SQL);
    pstmt.setString(1, className);/*from   ww  w .ja  va  2 s .  com*/
    pstmt.setObject(2, object);
    pstmt.executeUpdate();
    ResultSet rs = pstmt.getGeneratedKeys();
    int id = -1;
    if (rs.next()) {
        id = rs.getInt(1);
    }
    rs.close();
    pstmt.close();
    return id;
}

From source file:net.sf.sprockets.sql.Statements.java

/**
 * Execute the insert statement, get the first generated key as a long, and close the statement.
 * /*from www.ja v  a  2s. c  o m*/
 * @param stmt
 *            must have been created with {@link Statement#RETURN_GENERATED_KEYS} and already
 *            have parameters set
 * @return 0 if the statement did not generate any keys
 */
public static long firstLongKey(PreparedStatement stmt) throws SQLException {
    stmt.execute();
    ResultSet rs = stmt.getGeneratedKeys();
    long l = rs.next() ? rs.getLong(1) : 0L;
    stmt.close();
    return l;
}

From source file:SerializeJavaObjects_MySQL.java

public static long writeJavaObject(Connection conn, Object object) throws Exception {
    String className = object.getClass().getName();
    PreparedStatement pstmt = conn.prepareStatement(WRITE_OBJECT_SQL);

    // set input parameters
    pstmt.setString(1, className);/*from   ww  w  . j av a2 s.  com*/
    pstmt.setObject(2, object);
    pstmt.executeUpdate();

    // get the generated key for the id
    ResultSet rs = pstmt.getGeneratedKeys();
    int id = -1;
    if (rs.next()) {
        id = rs.getInt(1);
    }

    rs.close();
    pstmt.close();
    System.out.println("writeJavaObject: done serializing: " + className);
    return id;
}

From source file:org.biblionum.ouvrage.modele.CategorieOuvrageModele.java

/**
 * Java method that inserts a row in the generated sql table and returns the
 * new generated id//ww  w . j  av  a  2  s  .co m
 *
 * @param con (open java.sql.Connection)
 * @param designation_categorie
 * @return id (database row id [id])
 * @throws SQLException
 */
public static int insertIntoCategorieouvrage(DataSource ds, String designation_categorie) throws SQLException {

    con = ds.getConnection();
    int generatedId = -1;
    String sql = "INSERT INTO categorieouvrage (designation_categorie)" + "VALUES (?)";
    PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, designation_categorie);
    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.forumj.dbextreme.db.service.test.user.tests.ReadUserTest.java

private static void executeSql(PreparedStatement st, IUser user) throws SQLException {
    st.executeUpdate();/*from w  ww .ja  v a  2 s .  co  m*/
    ResultSet idRs = st.getGeneratedKeys();
    if (idRs.next()) {
        user.setId(idRs.getLong(1));
    }
}

From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java

public static int insertIntoOuvragetype(DataSource ds, String contenu_commentaire, int utilisateurid,
        int ouvrageid) throws SQLException {
    Connection con = ds.getConnection();
    int generatedId = -1;
    String sql = "INSERT INTO ouvragetype (contenu_commentaire, utilisateurid, ouvrageid)" + "VALUES (?, ?, ?)";
    PreparedStatement statement = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    statement.setString(1, contenu_commentaire);

    statement.setInt(2, utilisateurid);/*from w  w  w.  j  a v a  2 s . c o m*/
    statement.setInt(3, ouvrageid);
    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: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  .j  a va 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:com.keybox.manage.db.SessionAuditDB.java

/**
 * insert new session record for user/*from  ww w.j  a  v a 2  s. c  om*/
 *
 * @param con    DB connection
 * @param userId user id
 * @return session id
 */
public static Long createSessionLog(Connection con, Long userId) {
    Long sessionId = null;
    try {

        //insert
        PreparedStatement stmt = con.prepareStatement("insert into session_log (user_id) values(?)",
                Statement.RETURN_GENERATED_KEYS);
        stmt.setLong(1, userId);
        stmt.execute();
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs != null && rs.next()) {
            sessionId = rs.getLong(1);
        }

        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    return sessionId;

}