Example usage for java.sql ResultSet getBigDecimal

List of usage examples for java.sql ResultSet getBigDecimal

Introduction

In this page you can find the example usage for java.sql ResultSet getBigDecimal.

Prototype

BigDecimal getBigDecimal(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.math.BigDecimal with full precision.

Usage

From source file:nl.tudelft.stocktrader.derby.DerbyCustomerDAO.java

public Account login(String userId, String password) throws DAOException {
    PreparedStatement selectCustomerProfileByUserId = null;
    PreparedStatement updateCustomerLogin = null;
    PreparedStatement selectCustomerLogin = null;
    try {//from  w  w  w . jav a  2 s  . c o m
        selectCustomerProfileByUserId = sqlConnection.prepareStatement(SQL_SELECT_CUSTOMER_PROFILE_BY_USERID);
        selectCustomerProfileByUserId.setString(1, userId);
        ResultSet customerProfileRS = selectCustomerProfileByUserId.executeQuery();
        if (customerProfileRS.next()) {
            try {
                String userPassword = customerProfileRS.getString(2);
                if (userPassword.equals(password)) {
                    try {
                        updateCustomerLogin = sqlConnection.prepareStatement(SQL_UPDATE_CUSTOMER_LOGIN);
                        updateCustomerLogin.setString(1, userId);
                        updateCustomerLogin.executeUpdate();
                        selectCustomerLogin = sqlConnection.prepareStatement(SQL_SELECT_CUSTOMER_LOGIN);
                        selectCustomerLogin.setString(1, userId);
                        ResultSet rs = selectCustomerLogin.executeQuery();
                        if (rs.next()) {
                            try {
                                Account accountData = new Account(rs.getInt(1), userId,
                                        StockTraderUtility.convertToCalendar(rs.getDate(2)),
                                        rs.getBigDecimal(3), rs.getInt(4), rs.getBigDecimal(5),
                                        StockTraderUtility.convertToCalendar(rs.getDate(6)), rs.getInt(7));
                                return accountData;
                            } finally {
                                try {
                                    rs.close();
                                } catch (SQLException e) {
                                    logger.debug("", e);
                                }
                            }
                        }
                    } catch (SQLException e) {
                        throw new DAOException("", e);
                    } finally {
                        if (updateCustomerLogin != null) {
                            try {
                                updateCustomerLogin.close();
                            } catch (SQLException e) {
                                logger.debug("", e);
                            }
                        }
                        if (selectCustomerLogin != null) {
                            try {
                                selectCustomerLogin.close();
                            } catch (SQLException e) {
                                logger.debug("", e);
                            }
                        }
                    }
                }
            } finally {
                try {
                    customerProfileRS.close();
                } catch (SQLException e) {
                    logger.debug("", e);
                }
            }
        }

    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        if (selectCustomerProfileByUserId != null) {
            try {
                selectCustomerProfileByUserId.close();
            } catch (SQLException e) {
                logger.debug("", e);
            }
        }
    }
    return null;
}

From source file:org.openbravo.test.accounting.RecordID2Test.java

private BigDecimal getBalance(String strRecordID2, String strTableId, String strCAcctSchemaId,
        String strAccountId) {/*from   ww  w.ja  v a 2s.com*/
    String sql = "select coalesce(sum(amtacctdr-amtacctcr),0) " //
            + "from fact_Acct where record_ID2 = ?" + " and ad_table_id = ?"
            + " and c_acctschema_id = ? and account_id = ?";

    PreparedStatement sqlQuery = null;
    ResultSet rs = null;
    try {
        sqlQuery = new DalConnectionProvider(false).getPreparedStatement(sql);
        sqlQuery.setString(1, strRecordID2);
        sqlQuery.setString(2, strTableId);
        sqlQuery.setString(3, strCAcctSchemaId);
        sqlQuery.setString(4, strAccountId);
        sqlQuery.execute();
        sqlQuery.setMaxRows(1);
        rs = sqlQuery.getResultSet();
        while (rs.next()) {
            return rs.getBigDecimal(1);
        }
    } catch (Exception e) {
        assertFalse(true);
        log.error("Error when executing query", e);
    } finally {
        try {
            if (sqlQuery != null) {
                sqlQuery.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            log.error("Error when closing statement", e);
        }
    }
    return BigDecimal.ZERO;
}

From source file:org.kuali.kfs.gl.dataaccess.impl.TrialBalanceDaoJdbc.java

@Override
public List<TrialBalanceReport> findBalanceByFields(String selectedFiscalYear, String chartCode,
        String periodCode) {/* w  w w. ja  v  a2s. c  o  m*/
    final List<TrialBalanceReport> report = new ArrayList<TrialBalanceReport>();
    List<Object> queryArguments = new ArrayList<Object>(2);

    String YTDQuery = buildYTDQueryString(periodCode);
    StringBuilder queryBuilder = new StringBuilder();
    queryBuilder.append("SELECT A0.FIN_OBJECT_CD, A0.FIN_COA_CD, A1.FIN_OBJ_CD_NM, A2.FIN_OBJTYP_DBCR_CD,");
    queryBuilder.append(YTDQuery + " AS YTD ");
    queryBuilder.append(
            "FROM GL_BALANCE_T A0 JOIN CA_OBJECT_CODE_T A1 on A1.FIN_COA_CD = A0.FIN_COA_CD AND A1.UNIV_FISCAL_YR = A0.UNIV_FISCAL_YR and A1.FIN_OBJECT_CD = A0.FIN_OBJECT_CD ");
    queryBuilder.append("JOIN CA_OBJ_TYPE_T A2 on A2.FIN_OBJ_TYP_CD = A1.FIN_OBJ_TYP_CD ");
    queryBuilder.append("JOIN CA_ACCTG_CTGRY_T A3 on A3.ACCTG_CTGRY_CD = A2.ACCTG_CTGRY_CD ");
    queryBuilder.append("WHERE A0.FIN_BALANCE_TYP_CD = 'AC' ");
    queryBuilder.append("AND A0.UNIV_FISCAL_YR = ? ");
    queryArguments.add(selectedFiscalYear);

    if (StringUtils.isNotBlank(chartCode)) {
        queryBuilder.append("AND A0.FIN_COA_CD=? ");
        queryArguments.add(chartCode);
    }
    queryBuilder.append(
            "GROUP BY A0.FIN_OBJECT_CD, A0.FIN_COA_CD, A1.FIN_OBJ_CD_NM, A2.FIN_OBJTYP_DBCR_CD, A3.FIN_REPORT_SORT_CD ");
    queryBuilder.append("HAVING " + YTDQuery + " <> 0 ");
    queryBuilder.append("ORDER BY A0.FIN_COA_CD, A3.FIN_REPORT_SORT_CD, A0.FIN_OBJECT_CD");

    getJdbcTemplate().query(queryBuilder.toString(), queryArguments.toArray(), new ResultSetExtractor() {
        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {

            TrialBalanceReport reportLine = null;
            KualiDecimal ytdAmount = null;
            KualiDecimal totalDebit = KualiDecimal.ZERO;
            KualiDecimal totalCredit = KualiDecimal.ZERO;
            String objectTypeDebitCreditCd = null;
            int index = 1;

            // Iterator the search result and build the lookup object for trial balance report
            while (rs != null && rs.next()) {
                reportLine = new TrialBalanceReport();
                reportLine.setIndex(index++);
                reportLine.setChartOfAccountsCode(rs.getString("FIN_COA_CD"));
                reportLine.setObjectCode(rs.getString("FIN_OBJECT_CD"));
                reportLine.setFinancialObjectCodeName(rs.getString("FIN_OBJ_CD_NM"));
                objectTypeDebitCreditCd = rs.getString("FIN_OBJTYP_DBCR_CD");
                ytdAmount = new KualiDecimal(rs.getBigDecimal("YTD"));

                if ((ytdAmount.isPositive() && KFSConstants.GL_CREDIT_CODE.equals(objectTypeDebitCreditCd))
                        || (ytdAmount.isNegative()
                                && KFSConstants.GL_DEBIT_CODE.equals(objectTypeDebitCreditCd))) {
                    reportLine.setCreditAmount(ytdAmount.abs());
                    // sum the total credit
                    totalCredit = totalCredit.add(reportLine.getCreditAmount());
                } else if ((ytdAmount.isPositive()
                        && KFSConstants.GL_DEBIT_CODE.equals(objectTypeDebitCreditCd))
                        || (ytdAmount.isNegative()
                                && KFSConstants.GL_CREDIT_CODE.equals(objectTypeDebitCreditCd))) {
                    reportLine.setDebitAmount(ytdAmount.abs());
                    // sum the total debit
                    totalDebit = totalDebit.add(reportLine.getDebitAmount());
                }
                report.add(reportLine);
            }

            // add a final line for total credit and debit
            if (!report.isEmpty()) {
                reportLine = new TrialBalanceReport();
                reportLine.setIndex(index++);
                reportLine.setChartOfAccountsCode("Total");
                reportLine.setDebitAmount(totalDebit);
                reportLine.setCreditAmount(totalCredit);
                report.add(reportLine);
            }
            return null;
        }
    });
    return report;
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

private void checkColumnBigDecimal(ResultSet rs, int column, int i, String bd) throws SQLException {
    BigDecimal bd1 = rs.getBigDecimal(column);
    int i1 = rs.getInt(column);
    if (bd == null) {
        trace("should be: null");
        assertTrue(rs.wasNull());// www. j a va2 s  .  c  o  m
    } else {
        trace("BigDecimal i=" + i + " bd=" + bd + " ; i1=" + i1 + " bd1=" + bd1);
        assertTrue(!rs.wasNull());
        assertTrue(i1 == i);
        assertTrue(bd1.compareTo(new BigDecimal(bd)) == 0);
    }
}

From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStore.java

private PageStats getPageStats(String pageStatsKey) {
    String getPageStats = dialect.getPageStats(schema, "key");
    return jt.queryForOptionalObject(getPageStats, new ParameterizedRowMapper<PageStats>() {

        public PageStats mapRow(ResultSet rs, int rowNum) throws SQLException {
            PageStats ps = new PageStats(0);
            // FREQUENCY_OF_USE, LAST_ACCESS_TIME, FILL_FACTOR, NUM_HITS FROM
            ps.setFrequencyOfUsePerMinute(rs.getFloat(1));
            ps.setLastAccessMinutes(rs.getInt(2));
            ps.setFillFactor(rs.getFloat(3));
            ps.setNumHits(rs.getBigDecimal(4).toBigInteger());

            return ps;
        }/*from  w ww .  jav a  2 s  .  c om*/
    }, Collections.singletonMap("key", pageStatsKey));
}

From source file:com.erbjuder.logger.server.rest.util.ResultSetConverter.java

private List<LogMessage> toLogMessageInternal(ResultSet rs, List<LogMessage> logMessages) {

    try {//from   ww  w  . ja  va 2 s  .  c om

        // we will need the column names.
        java.sql.ResultSetMetaData rsmd = rs.getMetaData();
        //loop through the ResultSet
        while (rs.next()) {

            //figure out how many columns there are
            int numColumns = rsmd.getColumnCount();

            //each row in the ResultSet will be converted to a Object
            LogMessage obj = new LogMessage();

            // loop through all the columns 
            for (int i = 1; i < numColumns + 1; i++) {
                String column_name = rsmd.getColumnName(i);

                if (column_name.equals("ID")) {
                    obj.setId(rs.getBigDecimal(column_name).longValueExact());
                }

                if (column_name.equals("APPLICATIONNAME")) {
                    obj.setApplicationName(rs.getNString(column_name));
                }

                if (column_name.equals("EXPIREDDATE")) {
                    obj.setExpiredDate(rs.getDate(column_name));
                }

                if (column_name.equals("FLOWNAME")) {
                    obj.setFlowName(rs.getNString(column_name));
                }

                if (column_name.equals("FLOWPOINTNAME")) {
                    obj.setFlowPointName(rs.getNString(column_name));
                }

                if (column_name.equals("ISERROR")) {
                    obj.setIsError(rs.getBoolean(column_name));
                }

                if (column_name.equals("TRANSACTIONREFERENCEID")) {
                    obj.setTransactionReferenceID(rs.getNString(column_name));
                }

                if (column_name.equals("UTCLOCALTIMESTAMP")) {
                    obj.setUtcLocalTimeStamp(rs.getTimestamp(column_name));
                }

                if (column_name.equals("UTCSERVERTIMESTAMP")) {
                    obj.setUtcServerTimeStamp(rs.getTimestamp(column_name));
                }
            } //end foreach
            logMessages.add(obj);
        } //end while
    } catch (Exception e) {
        e.printStackTrace();
    }

    return logMessages;
}

From source file:org.imos.abos.netcdf.NetCDFfile.java

public String getFileName(Instrument sourceInstrument, Timestamp dataStartTime, Timestamp dataEndTime,
        String table, String dataType, String instrument) {
    //SimpleDateFormat nameFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    SimpleDateFormat nameFormatter = new SimpleDateFormat("yyyyMMdd");
    nameFormatter.setTimeZone(tz);/*from w  ww. ja va 2s.c  o  m*/

    String filename = "ABOS_NetCDF.nc";
    String deployment = mooring.getMooringID();
    String mooringName = deployment.substring(0, deployment.indexOf("-"));
    if (instrument != null) {
        deployment += "-" + instrument;
    }
    if (sourceInstrument != null) {
        String sn = sourceInstrument.getSerialNumber().replaceAll("[()_]", "").trim();
        deployment += "-" + sourceInstrument.getModel().trim() + "-" + sn;

        String SQL = "SELECT depth FROM mooring_attached_instruments WHERE mooring_id = "
                + StringUtilities.quoteString(mooring.getMooringID()) + " AND instrument_id = "
                + sourceInstrument.getInstrumentID();

        logger.debug("SQL : " + SQL);

        Connection conn = Common.getConnection();
        Statement proc;
        double depth = Double.NaN;
        try {
            proc = conn.createStatement();
            proc.execute(SQL);
            ResultSet results = (ResultSet) proc.getResultSet();
            results.next();
            logger.debug("instrument lookup " + results);
            depth = results.getBigDecimal(1).doubleValue();
            //depth = 30;
            logger.info("depth from database " + depth);

            proc.close();
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(AbstractDataParser.class.getName()).log(Level.SEVERE, null, ex);
        }
        deployment += "-" + String.format("%-4.0f", Math.abs(depth)).trim() + "m";
    }
    if (mooringName.startsWith("SAZ")) {
        addTimeBnds = true;
    }
    if (authority.equals("IMOS")) {
        // IMOS_<Facility-Code>_<Data-Code>_<Start-date>_<Platform-Code>_FV<File-Version>_<Product-Type>_END-<End-date>_C-<Creation_date>_<PARTX>.nc

        // IMOS_ABOS-SOTS_20110803T115900Z_PULSE_FV01_PULSE-8-2011_END-20120719T214600Z_C-20130724T051434Z.nc
        filename = //System.getProperty("user.home")
                //+ "/"
                "data/" + authority + "_" + facility + "_" + dataType + "_"
                        + nameFormatter.format(dataStartTime) + "_" + mooringName;

        if (table.startsWith("raw")) {
            filename += "_FV01";
        } else {
            filename += "_FV02"; // its a data product from the processed table                
        }
        filename += "_" + deployment + "_END-" + nameFormatter.format(dataEndTime) + "_C-";

        filename = filename.replaceAll("\\s+", "-"); // replace any spaces with a - character

        filename += nameFormatter.format(new Date(System.currentTimeMillis()));
        Log.debug("try file name " + filename);

        if (multiPart) {
            int n = 1;
            String fnNext = filename + String.format("_PART%02d.nc", n);
            File fn = new File(fnNext);
            while (fn.exists()) {
                Log.info("File exists " + fn);
                n++;
                fnNext = filename + String.format("_PART%02d.nc", n);
                fn = new File(fnNext);
            }
            filename = fnNext;
        } else {
            filename += ".nc";
        }
    } else if (authority.equals("OS")) {
        filename = "OS" + "_" + facility + "_" + deployment + "_D" + ".nc";
    }

    System.out.println("Next filename " + filename);

    return filename;
}

From source file:edu.ku.brc.specify.tasks.subpane.VisualQueryPanel.java

/**
 * @throws IOException /*from  w ww. j  a  va2 s.  c  om*/
 * 
 */
private void doSearch() throws IOException {
    final String CNT = "CNT";

    UIFieldFormatterIFace fieldFmt = null;
    if (typeCBX.getSelectedIndex() == 0) {
        fieldFmt = DBTableIdMgr.getFieldFormatterFor(CollectionObject.class, "catalogNumber");
    }

    final StringBuilder pmStr = new StringBuilder();
    final String placeMark = " <Placemark><name>%s - %d / %d</name><Point><coordinates>%8.5f, %8.5f, 5</coordinates></Point></Placemark>\n";

    polySB.setLength(0);
    boxSB.setLength(0);

    final JStatusBar statusBar = UIRegistry.getStatusBar();
    final UIFieldFormatterIFace fldFmt = fieldFmt;
    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            // fills pntList from polyline
            // polyline was filled via clicks on WorldWind
            totalNumRecords = BasicSQLUtils.getCountAsInt(buildSQL(true));

            availPoints.clear();
            model = (DefaultListModel) dbObjList.getModel();
            model.removeAllElements();
            topIdHash.clear();

            markers.clear();

            polygon = new Polyline(polyline.getPositions());
            polygon.setClosed(true);

            for (Position p : polyline.getPositions()) {
                polySB.append(String.format("    %8.5f, %8.5f, 20\n", p.longitude.degrees, p.latitude.degrees));
            }

            int maxThreshold = 1000;
            int index = 0;
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = DBConnection.getInstance().createConnection();
                stmt = conn.createStatement();

                int currCnt = 0;
                ResultSet rs = stmt.executeQuery(buildSQL(false));
                while (rs.next()) {
                    if (currCnt < maxThreshold) {
                        double lat = rs.getBigDecimal(2).doubleValue();
                        double lon = rs.getBigDecimal(3).doubleValue();

                        Position pos = Position.fromDegrees(lat, lon, 0.0);
                        // ZZZ                            
                        //                            if (GeometryMath.isLocationInside(pos, polygon.getPositions()))
                        //                            {
                        //                                LatLonPoint llp = new LatLonPoint(rs.getInt(1), lat, lon);
                        //                                String title = rs.getString(4);
                        //                                if (title != null)
                        //                                {
                        //                                    title = (fldFmt != null ? fldFmt.formatToUI(title) :title).toString();
                        //                                } else
                        //                                {
                        //                                    title = "N/A";
                        //                                }
                        //                                llp.setTitle(title);
                        //                                llp.setIndex(index++);
                        //                                availPoints.add(llp);
                        //                                markers.add(llp);
                        //                                topIdHash.add(llp.getLocId());
                        //                                System.out.println(index+" / "+currCnt+" In:      "+lat+",  "+lon);
                        //                                pmStr.append(String.format(placeMark, "In: ",index, currCnt, lon, lat));
                        //                                
                        //                            } else
                        //                            {
                        //                                System.out.println(index+" / "+currCnt+" Tossing: "+lat+",  "+lon);
                        //                                pmStr.append(String.format(placeMark, "Tossing: ", index, currCnt, lon, lat));
                        //                            }
                    }
                    currCnt++;
                    if (currCnt % 100 == 0) {
                        firePropertyChange(CNT, 0, currCnt);
                    }
                }
                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
                /*UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex);
                log.error("SQLException: " + ex.toString()); //$NON-NLS-1$
                lo .error(ex.getMessage());*/

            } finally {
                try {
                    if (stmt != null)
                        stmt.close();
                    if (conn != null)
                        conn.close();
                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex);
                    ex.printStackTrace();
                }
            }

            return null;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            super.done();

            if (doDebug) {
                try {
                    final String template = FileUtils.readFileToString(new File("template.kml"));
                    final PrintWriter pw = new PrintWriter(new File("debug.kml"));

                    String str = StringUtils.replace(template, "<!-- BOX -->", boxSB.toString());
                    str = StringUtils.replace(str, "<!-- POLYGON -->", polySB.toString());
                    str = StringUtils.replace(str, "<!-- PLACEMARKS -->", pmStr.toString());
                    pw.println(str);
                    pw.flush();
                    pw.close();
                } catch (IOException ex) {
                }
            }

            UIRegistry.clearSimpleGlassPaneMsg();
            statusBar.setProgressDone(STATUSBAR_NAME);

            for (LatLonPlacemarkIFace llp : markers) {
                model.addElement(llp);
            }

            if (markers.size() > 0) {
                wwPanel.placeMarkers(markers, null);
                searchBtn.setEnabled(false);

            } else {
                doClearAll(true);
                startBtn.setEnabled(false);
            }
            clearAllBtn.setEnabled(true);
            clearSearchBtn.setEnabled(true);
        }
    };

    statusBar.setIndeterminate(STATUSBAR_NAME, false);
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", "XXX"), 24);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                int value = (Integer) evt.getNewValue();
                int progress = (int) (((double) value / (double) totalNumRecords) * 100.0);
                glassPane.setProgress(progress);
                statusBar.setValue(STATUSBAR_NAME, progress);
            }
        }
    });
    worker.execute();
}

From source file:org.kuali.kfs.gl.batch.dataaccess.impl.LedgerPreparedStatementCachingDaoJdbc.java

public SufficientFundBalances getSufficientFundBalances(final Integer universityFiscalYear,
        final String chartOfAccountsCode, final String accountNumber, final String financialObjectCode) {
    return new RetrievingJdbcWrapper<SufficientFundBalances>() {
        @Override/*from w  w  w  .  j av a  2  s  . c  o m*/
        protected void populateStatement(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setInt(1, universityFiscalYear);
            preparedStatement.setString(2, chartOfAccountsCode);
            preparedStatement.setString(3, accountNumber);
            preparedStatement.setString(4, financialObjectCode);
        }

        @Override
        protected SufficientFundBalances extractResult(ResultSet resultSet) throws SQLException {
            SufficientFundBalances sufficientFundBalances = new SufficientFundBalances();
            sufficientFundBalances.setUniversityFiscalYear(universityFiscalYear);
            sufficientFundBalances.setChartOfAccountsCode(chartOfAccountsCode);
            sufficientFundBalances.setAccountNumber(accountNumber);
            sufficientFundBalances.setFinancialObjectCode(financialObjectCode);
            sufficientFundBalances.setAccountSufficientFundsCode(resultSet.getString(1));
            sufficientFundBalances.setCurrentBudgetBalanceAmount(new KualiDecimal(resultSet.getBigDecimal(2)));
            sufficientFundBalances.setAccountActualExpenditureAmt(new KualiDecimal(resultSet.getBigDecimal(3)));
            sufficientFundBalances.setAccountEncumbranceAmount(new KualiDecimal(resultSet.getBigDecimal(4)));
            return sufficientFundBalances;
        }
    }.get(SufficientFundBalances.class);
}

From source file:nz.co.gregs.dbvolution.actions.DBInsert.java

@Override
protected DBActionList execute(DBDatabase db) throws SQLException {
    final DBDefinition defn = db.getDefinition();
    DBRow row = getRow();//  www  . j a va  2s  .c o m
    DBActionList actions = new DBActionList(new DBInsert(row));

    DBStatement statement = db.getDBStatement();
    try {
        for (String sql : getSQLStatements(db)) {
            if (defn.supportsGeneratedKeys()) {
                try {
                    String primaryKeyColumnName = row.getPrimaryKeyColumnName();
                    Integer pkIndex = row.getPrimaryKeyIndex();
                    if (pkIndex == null || primaryKeyColumnName == null) {
                        statement.execute(sql);
                    } else {
                        if (primaryKeyColumnName.isEmpty()) {
                            statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
                        } else {
                            statement.execute(sql, new String[] { db.getDefinition()
                                    .formatPrimaryKeyForRetrievingGeneratedKeys(primaryKeyColumnName) });
                            pkIndex = 1;
                        }
                        if (row.getPrimaryKey().hasBeenSet() == false) {
                            ResultSet generatedKeysResultSet = statement.getGeneratedKeys();
                            try {
                                while (generatedKeysResultSet.next()) {
                                    final long pkValue = generatedKeysResultSet.getLong(pkIndex);
                                    if (pkValue > 0) {
                                        this.getGeneratedPrimaryKeys().add(pkValue);
                                        QueryableDatatype pkQDT = this.originalRow.getPrimaryKey();
                                        new InternalQueryableDatatypeProxy(pkQDT).setValue(pkValue);
                                        pkQDT = row.getPrimaryKey();
                                        new InternalQueryableDatatypeProxy(pkQDT).setValue(pkValue);
                                    }
                                }
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            } finally {
                                generatedKeysResultSet.close();
                            }
                        }
                    }
                } catch (SQLException sqlex) {
                    try {
                        sqlex.printStackTrace();
                        statement.execute(sql);
                    } catch (SQLException ex) {
                        throw new RuntimeException(sql, ex);
                    }
                }
            } else {
                try {
                    statement.execute(sql);
                    final QueryableDatatype primaryKey = row.getPrimaryKey();
                    if (primaryKey != null && primaryKey.hasBeenSet() == false
                            && defn.supportsRetrievingLastInsertedRowViaSQL()) {
                        String retrieveSQL = defn.getRetrieveLastInsertedRowSQL();
                        ResultSet rs = statement.executeQuery(retrieveSQL);
                        try {
                            QueryableDatatype originalPK = this.originalRow.getPrimaryKey();
                            QueryableDatatype rowPK = row.getPrimaryKey();
                            if ((originalPK instanceof DBInteger) && (rowPK instanceof DBInteger)) {
                                DBInteger inPK = (DBInteger) originalPK;
                                DBInteger inRowPK = (DBInteger) rowPK;
                                inPK.setValue(rs.getLong(1));
                                inRowPK.setValue(rs.getLong(1));
                            } else if ((originalPK instanceof DBNumber) && (rowPK instanceof DBInteger)) {
                                DBNumber inPK = (DBNumber) originalPK;
                                inPK.setValue(rs.getBigDecimal(1));
                                ((DBInteger) rowPK).setValue(rs.getLong(1));
                            } else if ((originalPK instanceof DBString) && (rowPK instanceof DBString)) {
                                DBString inPK = (DBString) originalPK;
                                inPK.setValue(rs.getString(1));
                                inPK = (DBString) rowPK;
                                inPK.setValue(rs.getString(1));
                            }
                        } finally {
                            rs.close();
                        }
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        statement.close();
    }
    DBInsertLargeObjects blobSave = new DBInsertLargeObjects(this.originalRow);
    actions.addAll(blobSave.execute(db));
    row.setDefined();
    return actions;
}