Java subsequent DB2 insertions -845 error - java

I am getting -845 SQL codes on a table insert:
nested exception is org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL
[INSERT INTO PIM30_POL_DETAILS VALUES(PREVIOUS VALUE FOR PIM_ORDER_ID_SEQ, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)];
SQL state [51035]; error code [-845]; DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29; nested exception is com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29] with root cause
com.ibm.db2.jcc.am.SqlException: DB2 SQL Error: SQLCODE=-845, SQLSTATE=51035, SQLERRMC=SHELTRU.PIM_ORDER_ID_SEQ, DRIVER=4.17.29
The Java code for this is:
#Transactional
public String insertIntoDatabase(final List<Policy> pols, final InspectionOrder order, final OrderReason reason){
String toReturn = PolicyDAO.transactionTemplate.execute(new TransactionCallback<String>() {
#Override
public String doInTransaction(TransactionStatus status) {
SqlParameterSource params = new BeanPropertySqlParameterSource(order);
PolicyDAO.namedParemeterJdbcTemplate.update(Queries.getInsertInspOrder(), params);
for(Policy p : pols){
params = new BeanPropertySqlParameterSource(p);
PolicyDAO.namedParemeterJdbcTemplate.update(Queries.getInsertPolDetails(), params);
}
return "Successfully ordered inspection(s)";
}
});
if(toReturn.equals("Successfully ordered inspection(s)")) return toReturn;
else return "Failed to order inspection(s)";
}
Both INSERT statements use a sequence, the first one uses NEXT VALUE FOR PIM_ORDER_ID_SEQ and the second one uses PREVIOUS VALUE FOR PIM_ORDER_ID_SEQ. I presume that the second insertion is being called before the first insertion is finished as I only get the error 5-10% of the time.
What can I do to combat this?

Related

SimpleJdbcInsert to table with dot in name

I am trying to use SimpleJdbcInsert to a table that happens to have a dot character in its name with dbo as default schema. I pass in a map of key values to be inserted.
insertMessage = new SimpleJdbcInsert(dataSource).withTableName("Trades.Transaction");
insertMessage.execute((Map)message);
The following exception appears:
PreparedStatementCallback; bad SQL grammar [INSERT INTO Trades.Transaction (Uid, StreamId, Version, ValidFrom, ValidTo, IsLatest, Direction, Quantity, Notional, TradeDate, Status, Action, SettlementAmount, SettlementCurrency, AccruedInterest, BookingAccountType, BookingAccountUid, BookingAccountName, BookingAccountLegalEntityId, BookingAccountLegalEntityShortName, BookingAccountRepUid, BookingAccountRepName, BookingAccountFacilitatorUid, BookingAccountFacilitatorName, BookingAccountFacilitatorTeamCode, ContraAccountType, ContraAccountUid, ContraAccountName, ContraAccountLegalEntityId, ContraAccountLegalEntityShortName, ContraAccountRepUid, ContraAccountRepName, ContraAccountFacilitatorUid, ContraAccountFacilitatorName, ContraAccountFacilitatorTeamCode, FacingAccountType, FacingAccountUid, FacingAccountName, FacingAccountLegalEntityId, FacingAccountLegalEntityShortName, FacingAccountRepUid, FacingAccountRepName, FacingAccountFacilitatorUid, FacingAccountFacilitatorName, FacingAccountFacilitatorTeamCode, OrigSystemIsElectronicChannel, OrigSystem, OrigSystemUid, OrigSystemStatus, OrigSystemType, OrigSystemVersion, OrigSystemErrors, DestSystemUid, DestSystem, DestSystemStatus, DestSystemType, DestSystemVersion, DestSystemErrors, StpSystemUid, StpSystem, StpSystemStatus, StpSystemType, StpSystemVersion, StpSystemErrors, GatewaySystem, GatewaySystemStatus, GatewaySystemType, GatewaySystemVersion, GatewaySystemErrors, SettlementSystemUid, SettlementSystemName, SettlementSystemStatus, SettlementSystemType, SettlementSystemVersion, SettlementSystemErrors, TransactionType, Price, Obligor, Receiver, QuoteDate, EffectiveDate, MaturityDate, UnitSize, MatchedStatus, MatchedTradeId, InstrumentDescription, BookingFacilitatorTeamCode, FxClientRate, Principal, AccruedDays, SalesCommissionCode, SalesCommissionAmount, SalesCommissionRate, SalesCommissionCcy, BrokerCommissionCode, BrokerCommissionAmount, BrokerCommissionRate, BrokerCommissionCcy, MarkupCommissionCode, MarkupCommissionAmount, MarkupCommissionRate, MarkupCommissionCcy, AddOnCommissionCode, AddOnCommissionAmount, AddOnCommissionRate, AddOnCommissionCcy, PhoneConfirmInd, PhoneConfirmBy, PhoneConfirmOn, SalesManagerReview, SalesManagerReviewComments, SalesManagerReviewTime, SalesManagerReviewIndicator, TradeManagerReview, TradeManagerReviewComments, TradeManagerReviewTime, TradeManagerReviewIndicator, EnteredOn, UpdatedOn, EnteredBy, GatewaySystemUid, OrigSystemNote1, OrigSystemNote2, OrigSystemNote3, DestSystemNote1, DestSystemNote2, DestSystemNote3, GatewayAllocFlag, QuotedAmount, LastModifiedBy, OrigTransactionId, OrigMarkitWireId, ContraAccountGlobalBook, BookingAccountGlobalBook, FXSettleAmount, SettlementLocation, AssignmentFeeCd, AssignmentFeeDesc, RiskFlagCd, RiskFlagDesc, FormPurchaseCd, FormPurchaseDesc, AccruedInterestCd, AccruedInterestDesc, EcnName, EcnId, ContraAccountLocation, BookingAccountLocation, isSuppressTrade, ContraAccountTradingSystem, BookingAccountTradingSystem, isAmend, RetailCommissionCode, RetailCommissionAmount, RetailCommissionRate, RetailCommissionCcy, ContraAccountADPAccountNo, AsOfTime, ClientCommission, MarketRate, DayCount, ExecutionStatus, LinkStreamId, Spread, RfqId, isWashGen, FxRateCurrencyPair, FxRateCalcMethod, isApprovedForNewIssueAllocation, TransactionReservationId, isEligibleForTradeSync) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is java.sql.SQLException: Incorrect syntax near the keyword 'Transaction'.
I believe I need a way to surround Trade.Transaction with [ ] characters so it interprets that as complete table name instead of schema.tableName. However, if I specify those in the table name like below
insertMessage = new SimpleJdbcInsert(dataSource).withTableName("[Trades.Transaction]");
a Spring exception occurs stating it can't find meta data and hence can't find column names to generate insert statement.
Does anyone know how I can resolve this?
Thanks

Year out of Range Exception

I am intermittently getting an exception while saving records in database. Trigerring re-save of the same object from UI works well but not sure why do I hit the exception first. ALl date fields are good. Has anyone encountered this issue ever?
org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: Could not execute JDBC batch update; uncategorized SQLException for SQL [insert into t_order (trade_id, product_type, trading_desk, trading_book, trader_portfolio, current_workflow_state, creation_date, trade_date, execution_time, last_modified_date, last_modified_by_sid, sales_desk_id, creator_desk_id, action, vcon_bbg_speed_dial, vcon_comments, vcon_id, vcon_status, marketer_comment, creator_sid, trader_sid, salesperson_sid, on_behalf_of_sid, cpty_id, cpty_client_code, cpty_qib_flag, instrument_id, factor, settlement_date, settlement_date_convention, linked_deal_id, price, notional, real_notional, principal, net_money, accrued_interest, price_mode, buy_sell, yield, grid_cv, total_cv, additonal_cv, markup, additional_cv_units, leg_type_string, issue_type, pair_off, client_clearing, settlement_method, invert_fx_flag, clean_price, fx_ccy, fx_rate, transaction_cost, fx_transaction_cost, fx_principal, fx_net_money, fx_accrued_interest, accrual_days, discount, revenue_cv_rate, revenue_bond_markup_rate, revenue_fx_rate, revenue_cv_total, revenue_bond_markup_total, revenue_fx_total, revenue_split_coverage, revenue_split_execution, fx_customer_branch, nack_message, trade_flat_flag, deal_region, sales_book, rdt_instrument_id, parent_transaction_id, order_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; SQL state [99999]; error code [17268]; Year out of range.; nested exception is java.sql.BatchUpdateException: Year out of range.
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.orm.hibernate3.HibernateAccessor.convertJdbcAccessException(HibernateAccessor.java:424)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:410)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:747)
at com.jpmorgan.salesone.traderouter.dao.DealDaoImpl.saveCashDeal(DealDaoImpl.java:29)
at com.jpmorgan.salesone.traderouter.dao.DealJSPBeanManager.saveNewCashDealBean(DealJSPBeanManager.java:106)

debugging SQL stored procedure call in java

Hi I have a Stored procedure call with around 30+ IN parameters. I need the know the values of the parameters which are in the call to the SP since I am getting incorrect results.
the call is something like this:
return "{call FORECASTS_PKG.GENERATE_FORECAST_TASK(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
I have currently set the breakpoint on the above statement. I see the individual parameters having the values, but wondering if the values are set properly since its wrong results. I am sure the order of the parameters matters here and the values must be set accordingly so that its in the same order as in the Database.
How do I see the values inside this call? I do the the XML reperesentation of the in the implemented toString() method but thats just printed in a different default order.
Once I see the values I can compare to the defeinition in the Database and see if the values are set in the correct order as expected.

SQL 1064 Syntax Error using a JDBC prepared statement

I have:
String query = "INSERT INTO Basestations VALUES(?, ?, ?, ?, ?, ?, ?,"
+ "?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement prep = conn.prepareStatement(query);
prep.setInt(1, profile.getNetworkId());
prep.setInt(2, profile.getBaseStationId());
prep.setInt(8, profile.getLoadLevel());
prep.setInt(11, profile.getPositionX());
prep.setInt(12, profile.getPositionY());
prep.setInt(13, profile.getPort());
prep.setDouble(3, profile.getSignalStrength());
prep.setDouble(4, profile.getFrequency());
prep.setDouble(6, profile.getMaxBitrate());
prep.setDouble(7, profile.getGuaranteedBitrate());
prep.setDouble(10, profile.getRange());
prep.setString(5, profile.getNetworkType());
prep.setString(9, profile.getProvider());
prep.setString(14, profile.getCharging());
prep.setBoolean(15, true);
prep.executeUpdate(query);
and i am getting:
INFO: SQL Exception:
INFO: State : 42000
INFO: Message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' at line 1
INFO: Error : 1064
what could be wrong?
You're passing an string representing an invalid SQL statement to the executeUpdate() method when you don't need to. Try just doing prep.executeUpdate();.
In your last line you don't need pass the variable query.
So change
prep.executeUpdate(query);
For:
prep.executeUpdate();
The main error is here:
// incorrect
prep.executeUpdate(query);
// correct
prep.executeUpdate();
But please try to put your SQL in the following form:
UPDATE table_name(field1, field2, field3) VALUES(?, ? ,?)
This will prevent your code from breaking if there is an update to the table.

SQLException - Generated keys not requested (MySQL)

I get this error when im making a new character to my game, in the CreateCharHandler it sends "saveToDb(false);" but when im ingame with another char i manually created i can saveToDb(true); with no error. please help, why is this happening?
http://i56.tinypic.com/oh1pn5.png
SaveToDb method http://pastebin.com/9sT5XBxp
line 3514 is:
ResultSet rs = ps.getGeneratedKeys();
Thanks in advance!
Your SQLException clearly states that:
You need to specify Statement.RETURN_GENERATED_KEYS to the
Statement.executeUpdate() or Connection.prepareStatement().
This can be achieved as follows (adding an additional value on Connection.prepareStatement() method):
String SQL = ""; //whatever my String is
PreparedStatement ps = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "value");
//Other necessary ps.setXXX() methods
//now update
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
The Statement.RETURN_GENERATED_KEYS is key here.
Hope this helps!
PS: Useful resource.
#Charlie berg, since you prefer being lazy, I changed line 13 of your code to include the Statement.RETURN_GENERATED_KEYS:
ps = con.prepareStatement("INSERT INTO characters (level, fame, str, dex, luk, `int`, exp, hp, mp, maxhp, maxmp, sp, ap, gm, skincolor, gender, job, hair, face, map, meso, hpMpUsed, spawnpoint, party, buddyCapacity, messengerid, messengerposition, mountlevel, mounttiredness, mountexp, equipslots, useslots, setupslots, etcslots, monsterbookcover, watchedcygnusintro, vanquisherStage, dojopoints, lastDojoStage, finishedDojoTutorial, vanquisherKills, matchcardwins, matchcardlosses, matchcardties, omokwins, omoklosses, omokties, givenRiceCakes, partyquestitems, jailtime, accountid, name, world) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
Also, Statement class is of package java.sql (make sure you import correctly). :-)
Oracle Documents:
If there is no indication that auto-generated columns should be made
available for retrieval, a call to Statement.getGeneratedKeys will
return a null ResultSet.
You should explicitly tell to JDBC That you want generated keys.
like this:
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
or
conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
and then you can use getGeneratedKeys().

Categories

Resources