List of usage examples for java.sql PreparedStatement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. From source file:org.ut.biolab.medsavant.server.serverapi.RegionSetManager.java
@Override public void addRegionSet(String sessID, String regionSetName, int genomeID, char delim, FileFormat fileFormat, int numHeaderLines, int fileID) throws IOException, SQLException, RemoteException, SessionExpiredException { Connection conn = ConnectionController.connectPooled(sessID); try {/* w ww. j a v a2 s . co m*/ // TODO: Since we're using the MyISAM engine for this table, rolling back has no effect. conn.setAutoCommit(false); //add region set InsertQuery query = MedSavantDatabase.RegionSetTableSchema.preparedInsert(RegionSetColumns.NAME); PreparedStatement prep = conn.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); prep.setString(1, regionSetName); prep.executeUpdate(); ResultSet rs = prep.getGeneratedKeys(); rs.next(); int regionSetID = rs.getInt(1); File f = NetworkManager.getInstance().getFileByTransferID(sessID, fileID); Iterator<String[]> i = ImportDelimitedFile.getFileIterator(f.getAbsolutePath(), delim, numHeaderLines, fileFormat); query = MedSavantDatabase.RegionSetMembershipTableSchema.preparedInsert(GENOME_ID, REGION_SET_ID, CHROM, START, END, DESCRIPTION); prep = conn.prepareStatement(query.toString()); while (i.hasNext() && !Thread.currentThread().isInterrupted()) { String[] line = i.next(); LOG.info(StringUtils.join(line, '\t')); prep.setInt(1, genomeID); prep.setInt(2, regionSetID); prep.setString(3, line[0]); prep.setString(4, line[1]); prep.setString(5, line[2]); prep.setString(6, line[3]); prep.executeUpdate(); } // Since this table is defined with the MyISAM engine, the rollback doesn't actually do anything. if (Thread.currentThread().isInterrupted()) { conn.rollback(); } else { conn.commit(); } conn.setAutoCommit(true); } finally { conn.close(); } }
From source file:net.mindengine.oculus.frontend.service.report.filter.JdbcFilterDAO.java
@Override public long createFilter(Filter filter) throws Exception { String sql = "insert into filters (name, description, user_id, date, filter) values (?,?,?,?,?)"; PreparedStatement ps = getConnection().prepareStatement(sql); ps.setString(1, filter.getName());//from ww w.j a v a 2s . c o m ps.setString(2, filter.getDescription()); ps.setLong(3, filter.getUserId()); ps.setTimestamp(4, new Timestamp(filter.getDate().getTime())); ps.setString(5, filter.getFilter()); logger.info(ps); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { return rs.getLong(1); } return 0; }
From source file:oscar.dms.EDocUtil.java
public static int addDocument(String demoNo, String docFileName, String docDesc, String docType, String docClass, String docSubClass, String contentType, String observationDate, String updateDateTime, String docCreator, String responsible, String reviewer, String reviewDateTime, String source, String sourceFacility) throws SQLException { Document doc = new Document(); doc.setDoctype(docType);/*w w w . j a va 2 s .c om*/ doc.setDocClass(docClass); doc.setDocSubClass(docSubClass); doc.setDocdesc(docDesc); doc.setDocfilename(docFileName); doc.setDoccreator(docCreator); doc.setResponsible(responsible); doc.setUpdatedatetime(MyDateFormat.getSysDate(updateDateTime)); doc.setStatus('A'); doc.setContenttype(contentType); doc.setPublic1(0); doc.setObservationdate(MyDateFormat.getSysDate(observationDate)); doc.setReviewer(reviewer); doc.setReviewdatetime(MyDateFormat.getSysDate(reviewDateTime)); doc.setSource(source); doc.setSourceFacility(sourceFacility); documentDao.persist(doc); int key = 0; if (doc.getDocumentNo() > 0) { String add_record_string2 = "insert into ctl_document values ('demographic',?,?,'A')"; Connection conn = DbConnectionFilter.getThreadLocalDbConnection(); PreparedStatement add_record = conn.prepareStatement(add_record_string2); add_record.setString(1, demoNo); add_record.setString(2, doc.getDocumentNo().toString()); add_record.executeUpdate(); ResultSet rs = add_record.getGeneratedKeys(); if (rs.next()) key = rs.getInt(1); add_record.close(); rs.close(); } return key; }
From source file:com.bc.fiduceo.db.AbstractDriver.java
@Override public int insert(Sensor sensor) throws SQLException { final PreparedStatement preparedStatement = connection .prepareStatement("INSERT INTO SENSOR VALUES(default, ?)", Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, sensor.getName()); preparedStatement.executeUpdate();// w ww .j av a 2 s. c o m final ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); if (generatedKeys.next()) { return generatedKeys.getInt(1); } return -1; }
From source file:mx.com.pixup.portal.dao.DisqueraDaoJdbc.java
@Override public Disquera insertDisquera(Disquera disquera) { Connection connection = DBConecta.getConnection(); PreparedStatement preparedStatement = null; ResultSet resultSet = null;//from www . j a v a 2 s . c o m String sql = "insert into disquera (nombre) values (?)"; try { preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, disquera.getNombre()); preparedStatement.execute(); resultSet = preparedStatement.getGeneratedKeys(); resultSet.next(); disquera.setId(resultSet.getInt(1)); return disquera; } catch (Exception e) { Logger.getLogger(DBConecta.class.getName()).log(Level.SEVERE, null, e); return null; } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } }
From source file:ca.fastenalcompany.jsonconfig.ProductJson.java
public int update(String query, String... params) { Connection conn = null;//from w w w.j a v a 2 s. 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 rowsEffect = pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); if (rs.next()) { result = rs.getInt(1); } else if (rowsEffect > 0) { result = Integer.parseInt(params[params.length - 1]); } } catch (SQLException ex) { ex.printStackTrace(); } finally { try { System.out.println(PropertyManager.getProperty("db_conn_closed")); if (conn != null) { conn.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } return result; }
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 w w.j a v a2 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:com.sql.EMail.java
/** * Inserts email message into email table. * * @param eml EmailMessageModel/*from www .j av a 2 s.co m*/ * @return Integer - generated key of the email */ public static int InsertEmail(EmailMessageModel eml) { Connection conn = null; PreparedStatement ps = null; try { conn = DBConnection.connectToDB(); String sql = "INSERT INTO EMail (" + "section, " + "emailFrom, " + "emailTo, " + "emailSubject, " + "sentDate, " + "receivedDate, " + "emailCC, " + "emailBCC, " + "emailBody, " + "emailBodyFileName, " + "readyToFile " + ") VALUES (" + "?, " //1 + "?, " //2 + "?, " //3 + "?, " //4 + "?, " //5 + "?, " //6 + "?, " //7 + "?, " //8 + "?, " //9 + "?, " //10 + "0)"; // Ready to File False ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(1, StringUtils.left(eml.getSection(), 4)); ps.setString(2, StringUtils.left(eml.getEmailFrom(), 200)); ps.setString(3, eml.getEmailTo()); ps.setString(4, eml.getEmailSubject()); ps.setTimestamp(5, eml.getSentDate()); ps.setTimestamp(6, eml.getReceivedDate()); ps.setString(7, eml.getEmailCC()); ps.setString(8, eml.getEmailBCC()); ps.setString(9, eml.getEmailBody()); ps.setString(10, eml.getEmailBodyFileName()); ps.executeUpdate(); ResultSet newRow = ps.getGeneratedKeys(); if (newRow.next()) { return newRow.getInt(1); } } catch (SQLException ex) { ExceptionHandler.Handle(ex); } finally { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(ps); } return 0; }
From source file:dao.MaterialDaoImplem.java
@Override public int insertMaterial(Material material) { try (Connection connection = dataSource.getConnection()) { String query = ("INSERT INTO Material (name, weight, manufacturer,cost,quantity) values(?,?,?,?,?)"); PreparedStatement stat = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); stat.setString(1, material.getName()); stat.setInt(2, material.getWeight()); stat.setString(3, material.getManufacturer()); stat.setInt(4, material.getCost()); stat.setInt(5, material.getQuantity()); stat.execute();//from ww w .ja va 2 s . c o m ResultSet res = stat.getGeneratedKeys(); if (res.next()) { return res.getInt(1); } else { throw new RuntimeException("? ? "); } } catch (Exception e) { throw new RuntimeException("Error:insertMaterial", e); } }
From source file:com.laxser.blitz.lama.provider.jdbc.PreparedStatementCallbackReturnId.java
@Override public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (setter != null) { setter.setValues(ps);/*from w w w . j a v a 2s .c om*/ } int updated = ps.executeUpdate(); if (updated == 0) { if (returnType.isArray()) { return Array.newInstance(wrappedIdType, 0); } else { return defaultValueOf(wrappedIdType); } } ResultSet keys = ps.getGeneratedKeys(); if (keys != null) { try { Object ret = null; if (returnType.isArray()) { keys.last(); int length = keys.getRow(); keys.beforeFirst(); ret = Array.newInstance(wrappedIdType, length); } for (int i = 0; keys.next(); i++) { Object value = mapper.mapRow(keys, i); if (value == null && idType.isPrimitive()) { // ?primitive??null?? value = defaultValueOf(wrappedIdType); } if (ret != null) { Array.set(ret, i + 1, value); } else { ret = value; break; } } return ret; } finally { JdbcUtils.closeResultSet(keys); } } else { if (returnType.isArray()) { return Array.newInstance(wrappedIdType, 0); } else { return defaultValueOf(wrappedIdType); } } }