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.ut.biolab.medsavant.server.serverapi.ProjectManager.java

@Override
public int addProject(String sessID, String name, CustomField[] fields)
        throws SQLException, RemoteException, SessionExpiredException {

    TableSchema table = MedSavantDatabase.ProjectTableSchema;
    InsertQuery query = new InsertQuery(table.getTable());
    query.addColumn(table.getDBColumn(ProjectTableSchema.COLUMNNAME_OF_NAME), name);

    Connection c = ConnectionController.connectPooled(sessID);
    PreparedStatement stmt = c.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

    stmt.execute();/*from  ww w  .  j a v  a  2s  .  com*/
    ResultSet res = stmt.getGeneratedKeys();
    res.next();

    int projID = res.getInt(1);

    PatientManager.getInstance().createPatientTable(sessID, projID, fields);
    c.close();
    return projID;
}

From source file:com.wso2telco.dep.ratecardservice.dao.CategoryDAO.java

public CategoryDTO addCategory(CategoryDTO category) throws BusinessException {

    Connection con = null;//w  w  w . ja  v  a2 s . c  o m
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer categoryId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.CATEGORY.getTObject());
        query.append(" (categoryname, categorycode, categorydesc, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addCategory : " + ps);

        ps.setString(1, category.getCategoryName());
        ps.setString(2, category.getCategoryCode());
        ps.setString(3, category.getCategoryDescription());
        ps.setString(4, category.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            categoryId = rs.getInt(1);
        }

        category.setCategoryId(categoryId);
    } catch (SQLException e) {

        log.error("database operation error in addCategory : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addCategory : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return category;
}

From source file:oscar.oscarLab.ca.all.Hl7textResultsData.java

public static void populateMeasurementsTable(String lab_no, String demographic_no) {
    MessageHandler h = Factory.getHandler(lab_no);

    java.util.Calendar calender = java.util.Calendar.getInstance();
    String day = Integer.toString(calender.get(java.util.Calendar.DAY_OF_MONTH));
    String month = Integer.toString(calender.get(java.util.Calendar.MONTH) + 1);
    String year = Integer.toString(calender.get(java.util.Calendar.YEAR));
    String hour = Integer.toString(calender.get(java.util.Calendar.HOUR));
    String min = Integer.toString(calender.get(java.util.Calendar.MINUTE));
    String second = Integer.toString(calender.get(java.util.Calendar.SECOND));
    String dateEntered = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + second + ":";

    try {/*from w  w w  .ja va2s.c  om*/

        Connection conn = DbConnectionFilter.getThreadLocalDbConnection();

        //Check for other versions of this lab
        String[] matchingLabs = getMatchingLabs(lab_no).split(",");
        //if this lab is the latest version delete the measurements from the previous version and insert the new ones

        int k = 0;
        while (k < matchingLabs.length && !matchingLabs[k].equals(lab_no)) {
            k++;
        }

        if (k != 0) {
            MeasurementsDeleted measurementsDeleted;

            String sql = "SELECT m.* FROM measurements m LEFT JOIN measurementsExt e ON m.id = measurement_id AND e.keyval='lab_no' WHERE e.val='"
                    + matchingLabs[k - 1] + "'";
            ResultSet rs = DBHandler.GetSQL(sql);
            while (rs.next()) {
                measurementsDeleted = new MeasurementsDeleted();
                measurementsDeleted.setType(oscar.Misc.getString(rs, "type"));
                measurementsDeleted
                        .setDemographicNo(Integer.valueOf(oscar.Misc.getString(rs, "demographicNo")));
                measurementsDeleted.setProviderNo(oscar.Misc.getString(rs, "providerNo"));
                measurementsDeleted.setDataField(oscar.Misc.getString(rs, "dataField"));
                measurementsDeleted.setMeasuringInstruction(oscar.Misc.getString(rs, "measuringInstruction"));
                measurementsDeleted.setComments(oscar.Misc.getString(rs, "comments"));
                measurementsDeleted.setDateObserved(UtilDateUtilities
                        .StringToDate(oscar.Misc.getString(rs, "dateObserved"), "yyyy-MM-dd hh:mm:ss"));
                measurementsDeleted.setDateEntered(UtilDateUtilities
                        .StringToDate(oscar.Misc.getString(rs, "dateEntered"), "yyyy-MM-dd hh:mm:ss"));
                measurementsDeleted.setOriginalId(Integer.valueOf(oscar.Misc.getString(rs, "id")));
                measurementsDeletedDao.persist(measurementsDeleted);

                sql = "DELETE FROM measurements WHERE id='" + oscar.Misc.getString(rs, "id") + "'";
                DBHandler.RunSQL(sql);
                //sql = "DELETE FROM measurementsExt WHERE measurement_id='"+oscar.Misc.getString(rs,"measurement_id")+"'";
                //DBHandler.RunSQL(sql);

            }

        }
        // loop through the measurements for the lab and insert them

        for (int i = 0; i < h.getOBRCount(); i++) {
            for (int j = 0; j < h.getOBXCount(i); j++) {

                String result = h.getOBXResult(i, j);

                // only insert if there is a result and it is supposed to be viewed
                if (result.equals("") || result.equals("DNR") || h.getOBXName(i, j).equals("")
                        || h.getOBXResultStatus(i, j).equals("DNS"))
                    continue;
                logger.debug("obx(" + j + ") should be inserted");
                String identifier = h.getOBXIdentifier(i, j);
                String name = h.getOBXName(i, j);
                String unit = h.getOBXUnits(i, j);
                String labname = h.getPatientLocation();
                String accession = h.getAccessionNum();
                String req_datetime = h.getRequestDate(i);
                String datetime = h.getTimeStamp(i, j);
                String olis_status = h.getOBXResultStatus(i, j);
                String abnormal = h.getOBXAbnormalFlag(i, j);
                if (abnormal != null && (abnormal.equals("A") || abnormal.startsWith("H"))) {
                    abnormal = "A";
                } else if (abnormal != null && abnormal.startsWith("L")) {
                    abnormal = "L";
                } else {
                    abnormal = "N";
                }
                String[] refRange = splitRefRange(h.getOBXReferenceRange(i, j));
                String comments = "";
                for (int l = 0; l < h.getOBXCommentCount(i, j); l++) {
                    comments += comments.length() > 0 ? "\n" + h.getOBXComment(i, j, l)
                            : h.getOBXComment(i, j, l);
                }

                String sql = "SELECT b.ident_code, type.measuringInstruction FROM measurementMap a, measurementMap b, measurementType type WHERE b.lab_type='FLOWSHEET' AND a.ident_code=? AND a.loinc_code = b.loinc_code and type.type = b.ident_code";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, identifier);
                String measType = "";
                String measInst = "";
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()) {
                    measType = oscar.Misc.getString(rs, "ident_code");
                    measInst = oscar.Misc.getString(rs, "measuringInstruction");
                } else {
                    logger.debug("CODE:" + identifier + " needs to be mapped");
                }

                sql = "INSERT INTO measurements (type, demographicNo, providerNo, dataField, measuringInstruction, dateObserved, dateEntered )VALUES (?, ?, '0', ?, ?, ?, ?)";
                logger.debug(sql);
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, measType);
                pstmt.setString(2, demographic_no);
                pstmt.setString(3, result);
                pstmt.setString(4, measInst);
                pstmt.setString(5, h.getTimeStamp(i, j));
                pstmt.setString(6, dateEntered);
                pstmt.executeUpdate();
                rs = pstmt.getGeneratedKeys();
                String insertID = null;
                if (rs.next())
                    insertID = oscar.Misc.getString(rs, 1);

                String measurementExt = "INSERT INTO measurementsExt (measurement_id, keyval, val) VALUES (?,?,?)";

                pstmt = conn.prepareStatement(measurementExt);

                logger.debug("Inserting into measurementsExt id " + insertID + " lab_no " + lab_no);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "lab_no");
                pstmt.setString(3, lab_no);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " abnormal " + abnormal);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "abnormal");
                pstmt.setString(3, abnormal);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " identifier " + identifier);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "identifier");
                pstmt.setString(3, identifier);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " name " + name);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "name");
                pstmt.setString(3, name);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " labname " + labname);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "labname");
                pstmt.setString(3, labname);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " accession " + accession);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "accession");
                pstmt.setString(3, accession);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug(
                        "Inserting into measurementsExt id " + insertID + " request_datetime " + req_datetime);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "request_datetime");
                pstmt.setString(3, req_datetime);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                logger.debug("Inserting into measurementsExt id " + insertID + " datetime " + datetime);
                pstmt.setString(1, insertID);
                pstmt.setString(2, "datetime");
                pstmt.setString(3, datetime);
                pstmt.executeUpdate();
                pstmt.clearParameters();

                if (olis_status != null && olis_status.length() > 0) {
                    logger.debug(
                            "Inserting into measurementsExt id " + insertID + " olis_status " + olis_status);
                    pstmt.setString(1, insertID);
                    pstmt.setString(2, "olis_status");
                    pstmt.setString(3, olis_status);
                    pstmt.executeUpdate();
                    pstmt.clearParameters();
                }

                if (unit != null && unit.length() > 0) {
                    logger.debug("Inserting into measurementsExt id " + insertID + " unit " + unit);
                    pstmt.setString(1, insertID);
                    pstmt.setString(2, "unit");
                    pstmt.setString(3, unit);
                    pstmt.executeUpdate();
                    pstmt.clearParameters();
                }

                if (refRange[0].length() > 0) {
                    logger.debug("Inserting into measurementsExt id " + insertID + " range " + refRange[0]);
                    pstmt.setString(1, insertID);
                    pstmt.setString(2, "range");
                    pstmt.setString(3, refRange[0]);
                    pstmt.executeUpdate();
                    pstmt.clearParameters();
                } else {
                    if (refRange[1].length() > 0) {
                        logger.debug(
                                "Inserting into measurementsExt id " + insertID + " minimum " + refRange[1]);
                        pstmt.setString(1, insertID);
                        pstmt.setString(2, "minimum");
                        pstmt.setString(3, refRange[1]);
                        pstmt.executeUpdate();
                        pstmt.clearParameters();
                    }

                    // add other_id to measurementsExt so that annotation can be linked up through casemgmt_note_link
                    logger.debug("Inserting into measurementsExt id " + insertID + " other_id " + i + "-" + j);
                    pstmt.setString(1, insertID);
                    pstmt.setString(2, "other_id");
                    pstmt.setString(3, i + "-" + j);
                    pstmt.executeUpdate();
                    pstmt.clearParameters();

                    pstmt.close();

                }
            }
        }

    } catch (Exception e) {
        logger.error("Exception in HL7 populateMeasurementsTable", e);
    }

}

From source file:com.adanac.module.blog.dao.RecordDao.java

public Integer saveOrUpdate(String id, String title, String username, String html, String content) {
    return execute(new TransactionalOperation<Integer>() {
        @Override//  ww  w .  j  a  v a 2 s.  co m
        public Integer doInConnection(Connection connection) {
            String insertSql = "insert into records (title,username,create_date,"
                    + "record,content) values (?,?,?,?,?)";
            String updateSql = "update records set title=?,username=?,create_date=?,record=?,content=? where id=?";
            try {
                PreparedStatement statement = null;
                if (StringUtils.isBlank(id)) {
                    statement = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);
                    statement.setString(1, title);
                    statement.setString(2, username);
                    statement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
                    statement.setString(4, html);
                    statement.setString(5, content);
                } else {
                    statement = connection.prepareStatement(updateSql);
                    statement.setString(1, title);
                    statement.setString(2, username);
                    statement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
                    statement.setString(4, html);
                    statement.setString(5, content);
                    statement.setInt(6, Integer.valueOf(id));
                }
                int result = statement.executeUpdate();
                if (result > 0 && StringUtils.isBlank(id)) {
                    ResultSet keyResultSet = statement.getGeneratedKeys();
                    if (keyResultSet.next()) {
                        return keyResultSet.getInt(1);
                    }
                }
                if (result > 0) {
                    return Integer.valueOf(id);
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return null;
        }
    });
}

From source file:com.quinsoft.zeidon.dbhandler.JdbcHandler.java

@Override
protected int executeStatement(View view, EntityDef entityDef, SqlStatement stmt) {
    String sql = stmt.getAssembledCommand();
    logSql(stmt);//ww w .ja va  2  s. com

    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        ps = prepareAndBind(stmt, sql, view, entityDef, stmt.commandType);

        if (stmt.commandType == SqlCommand.INSERT) {
            ps.executeUpdate();

            if (useDbGenerateKeys()) {
                generatedKeys = new ArrayList<Object>();
                ResultSet rs2 = ps.getGeneratedKeys();
                try {
                    while (rs2.next()) {
                        Integer i = rs2.getInt(1);
                        generatedKeys.add(i);
                    }
                } finally {
                    DbUtils.closeQuietly(rs2);
                }
            } else
                generatedKeys = null;

        } else if (stmt.commandType == SqlCommand.SELECT) {
            // This should be getting the count.
            rs = ps.executeQuery();
            return rs.getInt(1);
        } else {
            ps.execute();
        }
    } catch (Exception e) {
        throw ZeidonException.prependMessage(e, generateErrorMessageWithBoundAttributes(sql, entityDef, stmt));
    } finally {
        close(rs, ps);
    }

    return 0;
}

From source file:com.nabla.wapp.report.server.ReportManager.java

public int addReport(final Connection conn, final String reportName, @Nullable final String internalName,
        final InputStream design, final InputStream in) throws SQLException, DispatchException {
    // load and scan report design
    if (log.isDebugEnabled())
        log.debug("scanning report " + reportName);
    ReportDesign report;/*from  w  w  w. ja v a 2  s  .  c  o  m*/
    try {
        report = new Persister().read(ReportDesign.class, design);
    } catch (Exception e) {
        if (log.isErrorEnabled())
            log.error("fail to load report design", e);
        throw new InternalErrorException(Util.formatInternalErrorDescription(e));
    }
    // add report record
    final Integer roleId = getRole(conn, report.getRole());
    if (roleId == null) {
        if (log.isErrorEnabled())
            log.error("invalid role '" + report.getRole() + "' defined for report '" + reportName + "'");
        throw new DispatchException(ReportErrors.REPORT_DESIGN_INVALID_ROLE);
    }
    final String category = report.getCategory();
    if (!reportCategoryValidator.isValid(category)) {
        if (log.isErrorEnabled())
            log.error("invalid category '" + category + "' defined for report ' " + reportName + "'");
        throw new DispatchException(ReportErrors.REPORT_DESIGN_INVALID_CATEGORY);
    }
    final PreparedStatement stmt = conn.prepareStatement(
            "INSERT INTO report (name,internal_name,category,role_id,content) VALUES(?,?,?,?,?);",
            Statement.RETURN_GENERATED_KEYS);
    try {
        stmt.setString(1, report.getTitle());
        if (internalName != null)
            stmt.setString(2, internalName);
        else
            stmt.setNull(2, Types.VARCHAR);
        if (category != null)
            stmt.setString(3, category);
        else
            stmt.setNull(3, Types.VARCHAR);
        stmt.setInt(4, roleId);
        stmt.setBinaryStream(5, in);
        if (log.isDebugEnabled())
            log.debug("uploading report " + reportName);
        if (stmt.executeUpdate() != 1) {
            if (log.isErrorEnabled())
                log.error("failed to add internal report '" + reportName + "'");
            throw new InternalErrorException();
        }
        final ResultSet rsKey = stmt.getGeneratedKeys();
        try {
            rsKey.next();
            return rsKey.getInt(1);
        } finally {
            rsKey.close();
        }
    } finally {
        stmt.close();
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dos.PgLocationHistory.java

/**
 * Creates a brand new event.//w  w  w.ja v  a  2 s.  c o m
 * 
 * @param ipAddress
 *            of interest
 * @param location
 *            geocoded
 * @return a copy of the event.
 * @throws SegueDatabaseException
 *             - if there is a db error.
 * @throws JsonProcessingException
 *             - if we can't parse / serialize the json
 */
private LocationHistoryEvent createNewEvent(final String ipAddress, final Location location)
        throws SegueDatabaseException, JsonProcessingException {
    PreparedStatement pst;
    try (Connection conn = database.getDatabaseConnection()) {
        Date creationDate = new Date();

        PGobject jsonObject = new PGobject();
        jsonObject.setType("jsonb");
        jsonObject.setValue(new ObjectMapper().writeValueAsString(location));

        pst = conn.prepareStatement("INSERT INTO ip_location_history "
                + "(id, ip_address, location_information, created, last_lookup, is_current) "
                + "VALUES (DEFAULT, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);

        pst.setString(1, ipAddress);
        pst.setObject(2, jsonObject);
        pst.setTimestamp(3, new java.sql.Timestamp(creationDate.getTime()));
        pst.setTimestamp(4, new java.sql.Timestamp(creationDate.getTime()));
        pst.setBoolean(5, true);

        if (pst.executeUpdate() == 0) {
            throw new SegueDatabaseException("Unable to save location event.");
        }

        try (ResultSet generatedKeys = pst.getGeneratedKeys()) {
            if (generatedKeys.next()) {
                Long id = generatedKeys.getLong(1);
                return new PgLocationEvent(id, ipAddress, location, creationDate, creationDate);
            } else {
                throw new SQLException("Creating location event failed, no ID obtained.");
            }
        }

    } catch (SQLException e) {
        throw new SegueDatabaseException("Postgres exception", e);
    }
}

From source file:com.nortal.petit.orm.statement.InsertStatement.java

@Override
public void exec() {
    prepare();/*  w  ww .  ja  v a 2s .  c  o m*/
    if (!CollectionUtils.isEmpty(getBeans())) {
        if (getMapping().id() == null) {
            execBatchUpdate();
        } else {
            final KeyHolder keyHolder = new GeneratedKeyHolder();
            final InterceptorCalls interceptorCalls = new InterceptorCalls();
            getJdbcTemplate().execute(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    return con.prepareStatement(getSql(), Statement.RETURN_GENERATED_KEYS);
                }
            }, new PreparedStatementCallback<Object>() {
                @Override
                public Object doInPreparedStatement(PreparedStatement ps)
                        throws SQLException, DataAccessException {
                    MappingParamFunction<B> paramFunction = new MappingParamFunction<B>(getMapping());

                    for (B bean : getBeans()) {
                        paramFunction.setBean(bean);
                        Object[] params = getParams(paramFunction);
                        Object[] queryParams = params.length == 1 && params[0] instanceof Object[]
                                ? (Object[]) params[0]
                                : params;
                        interceptorCalls.setBeanValues(bean, queryParams);
                        ArgPreparedStatementSetter.setValues(ps, queryParams, 1);

                        ps.executeUpdate();
                        extractKeys(ps);
                    }
                    return null;
                }

                /**
                 * @param ps
                 * @throws SQLException
                 */
                private void extractKeys(PreparedStatement ps) throws SQLException {
                    ResultSet keys = ps.getGeneratedKeys();
                    if (keys != null) {
                        try {
                            RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
                                    new ColumnMapRowMapper(), 1);
                            keyHolder.getKeyList().addAll(rse.extractData(keys));
                        } finally {
                            JdbcUtils.closeResultSet(keys);
                        }
                    }
                }
            });

            try {
                Property<B, Object> idProperty = getMapping().id();
                for (int i = 0; i < getBeans().size(); i++) {
                    B bean = getBeans().get(i);
                    Object key = keyHolder.getKeyList().get(i).get(idProperty.column());
                    idProperty.write(bean, key);
                    interceptorCalls.setBeanId(bean, key);
                }
            } catch (Exception e) {
                throw new PersistenceException("InsertStatement.exec: unable to write bean primary key", e);
            }
            interceptorCalls.callInterceptor();
        }
    } else {
        getJdbcTemplate().update(getSql(), getParams(null));
    }
}

From source file:com.wso2telco.dep.ratecardservice.dao.RateTaxDAO.java

public RateTaxDTO addRateTax(RateTaxDTO rateTax) throws BusinessException {

    Connection con = null;/*w  w  w.  j a  v a2s. co  m*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer rateTaxId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.RATE_TAX.getTObject());
        query.append(" (rate_defid, taxid, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addRateTax : " + ps);

        ps.setInt(1, rateTax.getRateDefinition().getRateDefId());
        ps.setInt(2, rateTax.getTax().getTaxId());
        ps.setString(3, rateTax.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            rateTaxId = rs.getInt(1);
        }

        rateTax.setRateTaxId(rateTaxId);
    } catch (SQLException e) {

        log.error("database operation error in addRateTax : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addRateTax : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return rateTax;
}

From source file:mupomat.controller.ObradaKorisnik.java

@Override
public Korisnik dodajNovi(Korisnik entitet) {

    try {/*from   w w  w  . j  av a 2 s.  com*/
        Connection veza = MySqlBazaPodataka.getConnection();

        veza.setAutoCommit(false);

        PreparedStatement izraz = veza
                .prepareStatement("insert into osoba (oib,ime,prezime,email) values (?,?,?,?)");
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getIme());
        izraz.setString(3, entitet.getPrezime());
        izraz.setString(4, entitet.getEmail());
        izraz.executeUpdate();

        izraz = veza.prepareStatement(
                "insert into korisnik (oib,automat,datumregistracije,korisnickoime,lozinka,uloga,aktivan) values (?,?,now(),?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);
        izraz.setString(1, entitet.getOib());
        izraz.setString(2, entitet.getAutomat());
        izraz.setString(3, entitet.getKorisnickoIme());
        izraz.setString(4, DigestUtils.md5Hex(entitet.getLozinka()));
        izraz.setString(5, entitet.getUloga());
        izraz.setBoolean(6, entitet.isAktivan());
        izraz.executeUpdate();

        ResultSet rs = izraz.getGeneratedKeys();
        rs.next();
        entitet.setSifra(rs.getInt(1));

        izraz.close();
        veza.commit();
        veza.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        return null;
    }

    return entitet;
}