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.mskcc.cbio.portal.dao.DaoPatient.java

public static int addPatient(Patient patient) throws DaoException {
    Connection con = null;/*from   ww w .java 2  s  .c o  m*/
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = JdbcUtil.getDbConnection(DaoPatient.class);
        pstmt = con.prepareStatement("INSERT INTO patient (`STABLE_ID`, `CANCER_STUDY_ID`) VALUES (?,?)",
                Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, patient.getStableId());
        pstmt.setInt(2, patient.getCancerStudy().getInternalId());
        pstmt.executeUpdate();
        rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            cachePatient(new Patient(patient.getCancerStudy(), patient.getStableId(), rs.getInt(1)),
                    patient.getCancerStudy().getInternalId());
            return rs.getInt(1);
        }
        return -1;
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JdbcUtil.closeAll(DaoPatient.class, con, pstmt, rs);
    }
}

From source file:org.mskcc.cbio.portal.dao.DaoCnaEvent.java

/**
 * Add new event directly and return the auto increment value.
 * /*  ww  w. j  a  v a 2 s  .c om*/
 * @param cnaEvent
 * @return
 * @throws DaoException 
 */
private static long addCnaEventDirectly(CnaEvent cnaEvent) throws DaoException {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = JdbcUtil.getDbConnection(DaoClinicalAttribute.class);
        pstmt = con.prepareStatement(
                "INSERT INTO cna_event (" + "`ENTREZ_GENE_ID`," + "`ALTERATION` )" + " VALUES(?,?)",
                Statement.RETURN_GENERATED_KEYS);
        pstmt.setLong(1, cnaEvent.getEntrezGeneId());
        pstmt.setShort(2, cnaEvent.getAlteration().getCode());
        pstmt.executeUpdate();
        rs = pstmt.getGeneratedKeys();
        rs.next();
        long newId = rs.getLong(1);
        return newId;
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JdbcUtil.closeAll(DaoClinicalAttribute.class, con, pstmt, rs);
    }
}

From source file:org.mskcc.cbio.portal.dao.DaoCopyNumberSegmentFile.java

public static int addCopyNumberSegmentFile(CopyNumberSegmentFile copySegFile) throws DaoException {
    Connection con = null;/*from ww  w  .jav  a  2s  .  c o  m*/
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = JdbcUtil.getDbConnection(DaoCopyNumberSegmentFile.class);
        pstmt = con.prepareStatement(
                "INSERT INTO copy_number_seg_file (`CANCER_STUDY_ID`, `REFERENCE_GENOME_ID`, `DESCRIPTION`,`FILENAME`)"
                        + " VALUES (?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        pstmt.setInt(1, copySegFile.cancerStudyId);
        pstmt.setString(2, copySegFile.referenceGenomeId.toString());
        pstmt.setString(3, copySegFile.description);
        pstmt.setString(4, copySegFile.filename);
        pstmt.executeUpdate();
        rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            return rs.getInt(1);
        }
        return -1;
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JdbcUtil.closeAll(DaoCopyNumberSegment.class, con, pstmt, rs);
    }
}

From source file:SpaceInvaders_V4.Util.DBConnect.java

/**
 * Submit score to database//w w  w. ja va2 s  . c o  m
 *
 * @param userID user playerID
 * @param score game score
 * @param kills number of kill this game
 * @param powerUps number of powerUps collected
 * @param deaths number of deaths this game
 */
public static void submitScore(int userID, int score, int kills, int powerUps, int deaths) {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    int scoreID;

    try {
        conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
        stmt = conn.prepareStatement(
                "INSERT INTO `spaceinvaders_entity_score` (score, kills, power_ups, deaths) VALUES (?,?,?,?);",
                Statement.RETURN_GENERATED_KEYS);

        stmt.setInt(1, score);
        stmt.setInt(2, kills);
        stmt.setInt(3, powerUps);
        stmt.setInt(4, deaths);

        stmt.executeUpdate();
        rs = stmt.getGeneratedKeys();
        rs.next();
        scoreID = rs.getInt(1);

        stmt = conn.prepareStatement(
                "INSERT INTO `spaceinvaders_xref_player_scores` (player_id, score_id) VALUES (?,?)");
        stmt.setInt(1, userID);
        stmt.setInt(2, scoreID);
        stmt.executeUpdate();
    } catch (SQLException ex) {
        Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } finally {
        closeConnections(rs, stmt, conn);
    }

}

From source file:org.mskcc.cbio.portal.dao.DaoSample.java

public static int addSample(Sample sample) throws DaoException {
    Connection con = null;/*from   w  w w . jav a 2s.c  o m*/
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = JdbcUtil.getDbConnection(DaoSample.class);
        pstmt = con.prepareStatement("INSERT INTO sample "
                + "( `STABLE_ID`, `SAMPLE_TYPE`, `PATIENT_ID`, `TYPE_OF_CANCER_ID` ) " + "VALUES (?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, sample.getStableId());
        pstmt.setString(2, sample.getType().toString());
        pstmt.setInt(3, sample.getInternalPatientId());
        pstmt.setString(4, sample.getCancerTypeId());
        pstmt.executeUpdate();
        rs = pstmt.getGeneratedKeys();
        if (rs.next()) {
            cacheSample(new Sample(rs.getInt(1), sample.getStableId(), sample.getInternalPatientId(),
                    sample.getCancerTypeId()));
            return rs.getInt(1);
        }
        return -1;
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        JdbcUtil.closeAll(DaoSample.class, con, pstmt, rs);
    }
}

From source file:org.ut.biolab.medsavant.server.serverapi.AnnotationManager.java

public static int addAnnotation(String sessID, String prog, String vers, int refID, String path, boolean hasRef,
        boolean hasAlt, int type, boolean endInclusive) throws SQLException, SessionExpiredException {

    LOG.debug("Adding annotation...");

    TableSchema table = MedSavantDatabase.AnnotationTableSchema;
    InsertQuery query = MedSavantDatabase.AnnotationTableSchema.insert(PROGRAM, prog, VERSION, vers,
            REFERENCE_ID, refID, PATH, path, HAS_REF, hasRef, HAS_ALT, hasAlt, TYPE, type, IS_END_INCLUSIVE,
            endInclusive);//  w w w.  j ava2s .co  m

    PooledConnection c = ConnectionController.connectPooled(sessID);
    PreparedStatement stmt = c.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);
    stmt.execute();
    ResultSet res = stmt.getGeneratedKeys();
    res.next();

    int annotid = res.getInt(1);

    c.close();

    return annotid;
}

From source file:at.becast.youploader.database.SQLite.java

public static int saveTemplate(Template template) throws SQLException, IOException {
    PreparedStatement prest = null;
    ObjectMapper mapper = new ObjectMapper();
    String sql = "INSERT INTO `templates` (`name`, `data`) " + "VALUES (?,?)";
    prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    prest.setString(1, template.getName());
    prest.setString(2, mapper.writeValueAsString(template));
    prest.execute();/*from  ww w. java 2 s  .  c om*/
    ResultSet rs = prest.getGeneratedKeys();
    prest.close();
    if (rs.next()) {
        int id = rs.getInt(1);
        rs.close();
        return id;
    } else {
        return -1;
    }
}

From source file:module.entities.NameFinder.DB.java

/**
 * Starts the activity log/*w  ww  .  java  2 s.  c o m*/
 *
 * @param startTime - The start time of the crawling procedure
 * @return - The activity's log id
 * @throws java.sql.SQLException
 */
public static int LogRegexFinder(long startTime) throws SQLException {
    String insertLogSql = "INSERT INTO log.activities (module_id, start_date, end_date, status_id, message) VALUES (?,?,?,?,?)";
    PreparedStatement prepLogCrawlStatement = connection.prepareStatement(insertLogSql,
            Statement.RETURN_GENERATED_KEYS);
    prepLogCrawlStatement.setInt(1, 4);
    prepLogCrawlStatement.setTimestamp(2, new java.sql.Timestamp(startTime));
    prepLogCrawlStatement.setTimestamp(3, null);
    prepLogCrawlStatement.setInt(4, 1);
    prepLogCrawlStatement.setString(5, null);
    prepLogCrawlStatement.executeUpdate();
    ResultSet rsq = prepLogCrawlStatement.getGeneratedKeys();
    int crawlerId = 0;
    if (rsq.next()) {
        crawlerId = rsq.getInt(1);
    }
    prepLogCrawlStatement.close();
    return crawlerId;
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {// ww  w  .j a v  a 2 s.  c  om
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/** Get the automatically generated key that was created with the
 * just-executed statement.//from  w w  w .  ja  v a2s  .c om
 *
 * @param s A statement created with Statement.RETURN_GENERATED_KEYS
 * @return The single generated key
 * @throws SQLException If a database access error occurs or
 * the PreparedStatement is closed, or the JDBC driver does not support
 * the setGeneratedKeys() method
 */
public static long getGeneratedID(PreparedStatement s) throws SQLException {
    ArgumentNotValid.checkNotNull(s, "PreparedStatement s");
    ResultSet res = s.getGeneratedKeys();
    if (!res.next()) {
        throw new IOFailure("No keys generated by " + s);
    }
    return res.getLong(1);
}