List of usage examples for java.sql PreparedStatement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. From source file:org.ado.biblio.desktop.db.DatabaseConnection.java
public Book insertBook(Book book) throws SQLException { String query = "INSERT INTO Book (title, author, isbn, tags) VALUES (?,?,?,?)"; final PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); statement.setString(1, book.getTitle()); statement.setString(2, book.getAuthor()); statement.setString(3, book.getIsbn()); statement.setString(4, book.getTags()); final int i = statement.executeUpdate(); if (i == 0) { throw new SQLException("Update book failed, no rows affected."); }// w ww . jav a 2 s .c om final ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { final int id = resultSet.getInt(1); return new Book(id, book.getTitle(), book.getAuthor(), book.getIsbn(), new java.util.Date(), book.getTags()); } return null; }
From source file:Database.Handler.java
public int insertQuery(String sql, String[] para, Class outputClass) { PreparedStatement ps; try {// ww w . j a v a 2s . c o m Connection c = DriverManager.getConnection(DbConfig.connectionString, DbConfig.dbUserName, DbConfig.dbPassword); ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); for (int i = 0; i < para.length; i++) { ps.setString(i + 1, para[i]); } System.out.println(ps); ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } return -1; } catch (SQLException ex) { System.out.println("Handler insertQuery error:" + ex.getMessage()); return -1; } }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationMappingDAOImpl.java
@Override public int addApplicationMapping(int deviceId, int applicationId, int tenantId) throws DeviceManagementDAOException { Connection conn;/*from ww w.jav a2s. c om*/ PreparedStatement stmt = null; ResultSet rs = null; int mappingId = -1; try { conn = this.getConnection(); String sql = "INSERT INTO DM_DEVICE_APPLICATION_MAPPING (DEVICE_ID, APPLICATION_ID, " + "TENANT_ID) VALUES (?, ?, ?)"; stmt = conn.prepareStatement(sql, new String[] { "id" }); stmt.setInt(1, deviceId); stmt.setInt(2, applicationId); stmt.setInt(3, tenantId); stmt.execute(); rs = stmt.getGeneratedKeys(); if (rs.next()) { mappingId = rs.getInt(1); } return mappingId; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:mx.com.pixup.portal.dao.FormaPagoDaoJdbc.java
@Override public FormaPago insertFormaPago(FormaPago formaPago) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null;//ww w . j a va 2 s .c o m String sql = "insert into forma_pago (descripcion) values (?)"; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, formaPago.getDescripcion()); preparedStatement.execute(); connection.commit(); resultSet = preparedStatement.getGeneratedKeys(); resultSet.next(); formaPago.setId(resultSet.getInt(1)); return formaPago; } catch (Exception e) { } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } return null; }
From source file:com.adanac.module.blog.dao.RecordDao.java
public Integer save(String username, String title, String record, String content) { return execute(new TransactionalOperation<Integer>() { @Override/*from w w w . j a v a 2 s.c om*/ public Integer doInConnection(Connection connection) { String sql = "insert into records (username,title,record,content,create_date) values (?,?,?,?,?)"; try { PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, username); statement.setString(2, title); statement.setString(3, record); statement.setString(4, content); statement.setTimestamp(5, new Timestamp(System.currentTimeMillis())); int result = statement.executeUpdate(); if (result > 0) { ResultSet keyResultSet = statement.getGeneratedKeys(); if (keyResultSet.next()) { return keyResultSet.getInt(1); } } } catch (SQLException e) { throw new RuntimeException(e); } return null; } }); }
From source file:com.nabla.wapp.server.database.InsertStatement.java
public int execute(final Connection conn, final T record) throws SQLException, ValidationException, InternalErrorException { Assert.argumentNotNull(conn);/*from www .j a v a 2 s . c om*/ final List<IStatementParameter> parametersToInsert = new ArrayList<IStatementParameter>(); final ArgumentList names = new ArgumentList(); final ArgumentList values = new ArgumentList(); for (IStatementParameter parameter : parameters) { if (!parameter.include(record)) continue; parametersToInsert.add(parameter); names.add(parameter.getName()); values.add("?"); } if (parametersToInsert.isEmpty()) { if (log.isErrorEnabled()) log.error("no values to insert!!!!"); throw new InternalErrorException( Util.formatInternalErrorDescription("no parameter values given for SQL statement")); } final String sql = MessageFormat.format(sqlTemplate, names.toString(), values.toString()); if (log.isDebugEnabled()) log.debug("SQL=" + sql); final PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); try { int i = 1; for (IStatementParameter parameter : parametersToInsert) parameter.write(stmt, i++, record); if (stmt.executeUpdate() != 1) { if (log.isErrorEnabled()) log.error("failed to add record"); throw new InternalErrorException( Util.formatInternalErrorDescription("failed to execute SQL statement")); } final ResultSet rsKey = stmt.getGeneratedKeys(); try { rsKey.next(); return rsKey.getInt(1); } finally { Database.close(rsKey); } } catch (final SQLException e) { if (uniqueFieldName != null && SQLState.valueOf(e) == SQLState.INTEGRITY_CONSTRAINT_VIOLATION) { if (log.isErrorEnabled()) log.error("SQL error " + e.getErrorCode() + "-" + e.getSQLState(), e); throw new ValidationException(uniqueFieldName, CommonServerErrors.DUPLICATE_ENTRY); } throw e; } finally { Database.close(stmt); } }
From source file:mupomat.controller.ObradaOperater.java
@Override public Operater dodajNovi(Operater entitet) { try {//from w w w .j av a 2 s . co m Connection veza = MySqlBazaPodataka.getConnection(); PreparedStatement izraz = veza.prepareStatement( "insert into operater (korisnickoime,lozinka,ime,prezime,aktivan) values (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); izraz.setString(1, entitet.getKorisnickoIme()); izraz.setString(2, DigestUtils.md5Hex(entitet.getLozinka())); izraz.setString(3, entitet.getIme()); izraz.setString(4, entitet.getPrezime()); izraz.setBoolean(5, entitet.isAktivan()); izraz.executeUpdate(); ResultSet rs = izraz.getGeneratedKeys(); rs.next(); entitet.setSifra(rs.getInt(1)); rs.close(); izraz.close(); veza.close(); } catch (Exception e) { // System.out.println(e.getMessage()); e.printStackTrace(); return null; } return entitet; }
From source file:net.mindengine.oculus.frontend.service.issue.JdbcIssueDAO.java
@Override public void linkTestsToIssue(IssueCollation issueCollation) throws Exception { /*// www . ja v a2 s . c om * Inserting into issue_collations table first because then we will use * its generated index */ PreparedStatement ps = getConnection() .prepareStatement("insert into issue_collations (issue_id, reason_pattern) values (?,?)"); ps.setLong(1, issueCollation.getIssueId()); ps.setString(2, issueCollation.getReasonPattern()); logger.info(ps); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { issueCollation.setId(rs.getLong(1)); } else throw new Exception("An error appeared while linking tests to issue"); /* * Inserting all tests into issue_collation_tests table */ for (IssueCollationTest test : issueCollation.getTests()) { update("insert into issue_collation_tests (issue_collation_id, test_id, test_name) values (" + issueCollation.getId() + "," + test.getTestId() + ", :testName)", "testName", test.getTestName()); } update("update issues set dependent_tests = dependent_tests + :size where id = :id", "size", issueCollation.getTests().size(), "id", issueCollation.getIssueId()); /* * Inserting all conditions into issue_collation_conditions table */ for (IssueCollationCondition condition : issueCollation.getConditions()) { update("insert into issue_collation_conditions (issue_collation_id, trm_property_id, value) values (:issueCollationId, :trmPropertyId, :value)", "issueCollationId", issueCollation.getId(), "trmPropertyId", condition.getTrmPropertyId(), "value", condition.getValue()); } }
From source file:oobbit.orm.Links.java
/** * Add single new link.//w w w.j a v a2 s . co m * * @param link * * @return ID of the created link * * @throws SQLException */ public int add(Link link) throws SQLException { PreparedStatement statement = getConnection().prepareStatement( "INSERT INTO `oobbit`.`links`(`link_id`,`title`,`content`,`link`,`category`,`creator`,`create_time`,`edit_time`) " + "VALUES(NULL, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, NULL);", Statement.RETURN_GENERATED_KEYS); statement.setString(1, link.getTitle()); statement.setString(2, link.getContent()); statement.setString(3, link.getUrl()); statement.setString(4, link.getCategory()); statement.setInt(5, link.getCreatorId()); statement.executeUpdate(); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { return rs.getInt(1); } return -1; // failed }
From source file:com.microsoftopentechnologies.azchat.web.dao.UserPreferenceDAOImpl.java
/** * This method executes add user preference query on azure SQL user * preference table./*from w w w . j a v a2 s. c o m*/ * * @param userPreferenceEntity * @return * @throws Exception * @author Rupesh_Shirude */ @Override public UserPreferenceEntity addUserPreferenceEntity(UserPreferenceEntity userPreferenceEntity) throws Exception { LOGGER.info("[UserPreferenceEntity][addUserPreferenceEntity] start "); int userPreferenceId = 0; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = AzureChatUtils.getConnection(AzureChatUtils.buildConnectionString()); preparedStatement = connection.prepareStatement(AzureChatSQLConstants.ADD_USER_PREFERENCE, Statement.RETURN_GENERATED_KEYS); preparedStatement = generatePreparedStatement(preparedStatement, userPreferenceEntity); preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { userPreferenceId = resultSet.getInt(1); } } catch (SQLException e) { LOGGER.error( "Exception occurred while executing add user preference query on azure SQL user preference table. Exception Message : " + e.getMessage()); throw new AzureChatSystemException( "Exception occurred while executing add user preference query on azure SQL user preference table. Exception Message : " + e.getMessage()); } finally { AzureChatUtils.closeDatabaseResources(preparedStatement, resultSet, connection); } userPreferenceEntity.setUserPreferenceID(userPreferenceId); LOGGER.info("[UserPreferenceEntity][addUserPreferenceEntity] end "); return userPreferenceEntity; }