ResultSet
try
Statement s = connection.createStatement();
ResultSet rs = s.executeQuery("SELECT E.date, FROM Event E");
try
while (rs.next())
java.sql.Date eventDate = rs.getDate(1);
// Get Data from the Animal Table
Statement s2 = connection.createStatement();
ResultSet rs2 = s2.executeQuery("SELECT P.name, P.affiliation FROM ANIMAL P WHERE P.id=1");
System.out.prinltn(rs2.getString(1)) // CASUES AN EXCEPTION TO BE THROWN.
catch (SQLException sqle)
System.out.println("ERROR");
catch (SQLException e)
System.out.println("OUTER CATCH " + e.getMessage());
}I have no clue why I can't have two seperate ResultSet objects concurrently. They are initialized by seperate Statement objects. can anyone see the problem?
When I execute the second query in the MYSQL Query Browser GUI, it works fine.
Thank you.
ResultSet rs = s.executeQuery("SELECT E.date, FROM Event E");That's not valid SQL. There's a comma where there shouldn't be one.
db
Similar Messages
-
I'm getting desperate for a solution to this problem (as is the rest of the development team!).
Basically we've been trying to create a system that automatically assigns values (frequencies) to objects (nodes) based on a rule set. Each node contains a varying number of sub-objects (radios) and each radio needs one frequency. The database has been set up and has test data for our Solution class to go through. However, we've run into an odd problem where our ResultSets are suddenly closing.
The classes work like this:
Database Broker (handles connection to DB, as well as executeQuery and executeUpdate statements.)
Entry Broker (Holds all SQL statements for data retrieval in various methods. Each method contains an SQL statement to access data, and code to format that data into something useable by the main class.
Solution/Main class (Contains methods to use the data from the Entry Broker to test valid solutions. Certain rules apply to assigning frequencies to radios and this class ensures that the data applies to these rules before it writes the data back to the DB (via the EntryBroker).
The problem we continually run into is that whilst the ResultSets work fine in the Entry Broker, they are closed when they return to the Main class.
Here's the catch: It seems in most cases that only the FIRST ResultSet returned in each method is closed, the remaining ResultSets work fine. We worked around this problem by creating a 'dummy' ResultSet, which obtained data from the database which was never used (the project name). We put this in its own try catch bracket so it would not interrupt the project.
It worked fine for a few classes, but for others (notably the following one) it was ineffective. We've searched and searched but we cannot find anyone with a similar complaint (except a few people who have commented about ODBC version problems). Our ODBC version is 3.520.7713.0
Here's an example method from the Solution class (The entire class is over 1000 lines):
// Method to test Harmonic resonance for nodes within 10m
private boolean resonanceGlobal (boolean tstResonanceG, double txFreq, double rxFreq, int distance) {
System.out.println("Beginning global harmonic resonance check");
try {
// Getting Nodes
rsNode2 = eBroker.getNodes(projectNo);
// node loop
while (rsNode2.next()) {
System.out.println("602 Test Marker GHarm 1");
// get next node, store in nodeTemp
nodeTemp = rsNode2.getInt(1);
// System out to show which nodes will pass if statement
System.out.println(node + " compare to " + nodeTemp);
// avoid testing the same node against itself
if (nodeTemp != node) {
// distance check (only neccesary within 10m)
System.out.println("Test Marker Before Distance check");
distance = getDistance(node, nodeTemp, distance);
System.out.println("Test Marker After Distance check");
// distance check if statement
if (distance <= 10) {
System.out.println("618 Test Marker GHarm 2");
// get the radios of the node, foreign node
rsRadiosTemp = eBroker.getRadios(node);
rsDummy = eBroker.getDummy(projectNo);
rsRadios2 = eBroker.getRadios(nodeTemp);
// This dummy ResultSet normally fails so that
// the other ResultSets perform normally
try {
rsDummy.next();
} // end try
catch (java.sql.SQLException dummyException) {
System.out.println("dummyException " + dummyException);
} // end catch
// radio loop
while (rsRadiosTemp.next()) { // error occurs here
System.out.println("627 Test Marker GHarm 3");
// loop for foreign node radios
while (rsRadios2.next()) {
System.out.println("631 Test Marker GHarm 4");
// get next radio
radioTemp = rsRadios2.getInt(1);
// get the TX and RX of the radio
genericTX = getTX(radioTemp);
radioTempCon = getConnection(radioTemp);
genericRX = getTX(radioTempCon);
// calculate bounds for harmonics test
txLo = ((txFreq * 2) - genericTX) - 4; // 4Mhz below TX harmonics check
txHi = ((txFreq * 2) - genericTX) + 4; // 4Mhz above TX harmonics check
rxHi = ((rxFreq * 2) - genericRX) + 4; // 4Mhz above RX harmonics check
rxLo = ((rxFreq * 2) - genericRX) - 4; // 4Mhz below RX harmonics check
// checks TX and RX of foreign radio against TX, RX of current radio for separation
if ((txLo > genericTX && txHi < genericTX) || (rxLo > genericRX && rxHi < genericRX)) {
tstResonanceG = false;
break;
} //end if
else {
tstResonanceG = true;
} // end else
} //end foreign radio loop
// breaking out of loops for return
if (tstResonanceG == false)
break;
} // end radio loop
rsRadios2.close();
rsRadiosTemp.close();
} // end sameradio check
} // end distance check
}// end node loop
rsNode2.close();
} // end try
// Catch statement to stop from crashing in the
// event of an error during SQL statements.
catch (java.sql.SQLException resonanceGlobalException) {
// Prints out the error message produced
System.out.println(resonanceGlobalException);
} // end catch
// returns result
return tstResonanceG;
} //end checkHarmonicResonanceGlobal()
My apologies if it is a little hard to read, but the indenting is accurate. The Entry Broker methods which this method uses are here:
public ResultSet getNodes (int projectNo) {
// creating SQL statement
sqlStatement = "SELECT nodeNo from tblNode WHERE projectNo = " + projectNo;
System.out.println(sqlStatement);
// executing SQL statement
rsNodes = db.runQuery(sqlStatement);
// returns ResultSet
return rsNodes;
} // end getNodes
// Method to get the distance between any two nodes
public int getDistance (int projectNo, int node, int tempNode) {
ResultSet rsX1; // Used for obtaining the X-coord of node 1
ResultSet rsX2; // Used for obtaining the X-coord of node 2
ResultSet rsY1; // Used for obtaining the Y-coord of node 1
ResultSet rsY2; // Used for obtaining the Y-coord of node 2
double distance = 0; // Used in Global checks
int dist = 0; // Used in Global checks
int x1 = 0; // Used in calculating distance
int x2 = 0; // Used in calculating distance
int y1 = 0; // Used in calculating distance
int y2 = 0; // Used in calculating distance
int xDist = 0; // Used in calculating distance
int yDist = 0; // Used in calculating distance
int distint = 0; // Used to store converted values
try {
// get the X and Y co-ordinates of both nodes
sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
rsX1 = db.runQuery(sqlStatement);
rsX1.next();
x1 = rsX1.getInt(1);
sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
rsY1 = db.runQuery(sqlStatement);
rsY1.next();
y1 = rsY1.getInt(1);
sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
rsX2 = db.runQuery(sqlStatement);
rsX2.next();
x2 = rsX2.getInt(1);
sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
rsY2 = db.runQuery(sqlStatement);
rsY2.next();
y2 = rsY2.getInt(1);
} // end try
catch (java.sql.SQLException getDistanceException) {
System.out.println(getDistanceException);
// calculating distance
yDist = y2 - y1;
xDist = x2 - x1;
// perform pythagoras theorem for distance
dist = (xDist * xDist) + (yDist * yDist);
distance = java.lang.Math.sqrt(dist);
Double roundFreqTemp = new Double(freqTemp);
distint = roundFreqTemp.intValue() ;
return distint;
} // end get distance method
// Method to get all the radios in a node
public ResultSet getRadios(int node) {
ResultSet rsRadios; // Used for obtaining radios in a node
// creating sql Statement
sqlStatement = "SELECT * FROM tblRadio WHERE nodeNo =" + node;
System.out.println(sqlStatement);
// executing sql Statement
rsRadios = db.runQuery(sqlStatement);
System.out.println("EB Test Marker 1: Line 261");
// returning radio no
return rsRadios;
}//end getRadio
public double getTX(int radioTemp){
double txTemp = 0; // Used for storing TX of a radio
int freqNoTemp = 0; // Used for storing the frequency ID
rsDummy = getDummy(projectNo);
// creating SQL statement
sqlStatement ="Select frequencyNo from tblRadio where radioNo = " + radioTemp;
System.out.println(sqlStatement);
// executing SQL statement
rsTX = db.runQuery(sqlStatement);
try {
System.out.println("Test Marker EB1: 317");
try {
rsDummy.next();
} // end try
catch (java.sql.SQLException dummyException) {
System.out.println("dummyException" + dummyException);
} // end catch
System.out.println("Test MarkerEB2: 330");
// moving to first position in rs
rsTX.next();
System.out.println("Test MarkerEB3: 334");
// obtaining data from rs
freqNoTemp = rsTX.getInt(1);
System.out.println("Test MarkerEB4: 337");
rsTX.close();
} // end try
catch (java.sql.SQLException rsTXException) {
System.out.println("rsTXExeption: " + rsTXException);
} // emd catch
System.out.println("Frequency No is: " + freqNoTemp);
rsDummy = getDummy(projectNo);
sqlStatement = "Select frequency from tblFreq where frequencyNo = " + freqNoTemp;
System.out.println(sqlStatement);
rsRX = db.runQuery(sqlStatement);
try {
try {
System.out.println("Test MarkerEB6: 361");
rsDummy.next();
} // end try
catch (java.sql.SQLException dummyException) {
System.out.println("dummyException" + dummyException);
} // end catch
System.out.println("Test MarkerEB5: 373");
rsRX.next();
System.out.println("Test MarkerEB7: 376");
txTemp = rsRX.getDouble(1);
System.out.println("Test MarkerEB8: 379");
rsRX.close();
} // end try
catch (java.sql.SQLException rxException) {
System.out.println("rxException " + rxException);
} // end catch
System.out.println("393 Before return");
return txTemp;
} //end getTX
public int getConnection(int radio) {
int nodeCon = 0; // Used to return the connected node no
ResultSet rsConnection; // Used for obtaining the foreign radio
// creating SQL statement
sqlStatement = "SELECT radioNo FROM tblRadio where recRadio = " + radio;
System.out.println(sqlStatement);
// executing SQL statement
rsConnection = db.runQuery(sqlStatement);
try {
// moving to first position in rs
rsConnection.next();
// obtaining data from rs
nodeCon = rsConnection.getInt(1);
} // end try
catch (java.sql.SQLException getConnectionException) {
System.out.println("getConnectionException : " + getConnectionException);
} // end catch
// returns node no.
return nodeCon;
And finally, the dummy rs:
// Dummy method to fix resultSet closed error
public ResultSet getDummy (int projectNo) {
sqlStatement = "Select projectName from tblProject where projectNo = " + projectNo;
System.out.println(sqlStatement);
rsDummy = db.runQuery(sqlStatement);
return rsDummy;
Here is some sample output that we have:
----jGRASP exec: java MainGui
slider value constructor: 50
116: if(singleton==null) {
120: singleton=new Resolvotron
Connection to D/Base establised
Select projectName from tblProject where projectNo = 3
Init OK. Beginning solve process
main OK: beginning frequency assign process
SELECT nodeNo from tblNode WHERE projectNo = 3
267: Node number = 2
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Test Marker 1: Line 289
298: Radio number = 4
Test Marker 5: Line 308
Test Marker 3: Line 313
SELECT frequency from tblFreq WHERE projectNo = 3
125.5
Beginning test process
Test Marker 4: Line 386
Beginning check 257072
Test Marker 6: Line 774
70 Mhz Margin = false
Beginning local 10Mhz separation check
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Getting TX of radio: 4
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 4
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
432: getting connection
SELECT radioNo FROM tblRadio where recRadio = 4
438: getting TX of radio: 6
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 6
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
java.sql.SQLException: ResultSet is closed
10 Mhz Local = true
Beginning 10 Mhz separation check
SELECT nodeNo from tblNode WHERE projectNo = 3
Node number is 2
10 Mhz Global = false
Beginning local harmonic resonance check
SELECT * FROM tblRadio WHERE nodeNo =2
EB Test Marker 1: Line 261
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 4
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB5: 373
Test MarkerEB7: 376
Test MarkerEB8: 379
393 Before return
SELECT radioNo FROM tblRadio where recRadio = 4
Select projectName from tblProject where projectNo = 3
Select frequencyNo from tblRadio where radioNo = 6
Test Marker EB1: 317
dummyExceptionjava.sql.SQLException: ResultSet is closed
Test MarkerEB2: 330
Test MarkerEB3: 334
Test MarkerEB4: 337
Frequency No is: 2
Select projectName from tblProject where projectNo = 3
Select frequency from tblFreq where frequencyNo = 2
Test MarkerEB6: 361
I'll leave it at that, since the program goes into an endless loop. The dummy Exceptions are our dummy resultsets crashing so the rest can survive. The other stuff is from different methods. You should be able to locate the logic of the program by following the System.outs
Test Markers with EB refer to the Entry Broker.
Any help would be appreciated since we cannot find any other way of running this class successfully.
SteveOk problem solved...
Basically I was calling one ResultSet after another. Thanks to the Database Broker's structure, this was killing the first ResultSet. I fixed up the loops so that ResultSets were only ever called just before they were needed, and it fixed the problem. The only other errors were simple logic faults which I drummed out in short order. Thanks for the help everyone! -
IS it possible to define two resultset objects with two different queries inside the same DB class?java.sql.SQLException: Invalid state, the ResultSet object is closed.
at net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:299)
at net.sourceforge.jtds.jdbc.MSCursorResultSet.next(MSCursorResultSet.java:1123)
at DB5.getDetails(Daily_Quote_Response_report.java:238)
at Daily_Quote_Response_report.main(Daily_Quote_Response_report.java:74)
java.util.List items = null;
String query;
String query2;
try {
query =
"select * from oqrep_except_resp_summary";
query2 = "select * from oqrep_except_resp_detail";
Statement state = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = state.executeQuery(query);
ResultSet rs2 = state.executeQuery(query2);
//cannot create two rs objects // ResultSet rs2 = state.executeQuery(query);
items = new ArrayList();Edited by: bobz on 03-Dec-2009 11:16
Edited by: bobz on 03-Dec-2009 11:16Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.
-
Error while assigning resultset value to Querytable variable in Coldfusion 10
We are upgrading from coldfusion 8 to 10. Internally we were using java function to to get the data.
In java function we have a resultset object, if we assign this resultset value to Querytable variable, we are getting below error. This code was working fine in coldfusion 8.
Detail This exception is usually caused by service startup failure. Check your server configuration.
Message The Runtime service is not available.
StackTrace coldfusion.server.ServiceFactory$ServiceNotAvailableException: The Runtime service is not available. at coldfusion.server.ServiceFactory.getRuntimeService(ServiceFactory.java:117) at coldfusion.runtime.RequestMonitor.<clinit>(RequestMonitor.java:14) at coldfusion.sql.QueryTable.populate(QueryTable.java:358) at coldfusion.sql.QueryTable.populate(QueryTable.java:283) at coldfusion.sql.QueryTable.<init>(QueryTable.java:96) at com.myCompany.myClass.myFunct(myClass.java:627) at
Here is the function which is causing error.
static private QueryTable myFunct(String userId, SessionFactory sf) {
PreparedStatement pStmt = null;
ResultSet rs = null;
QueryTable ret = null;
try{
Query q = sf.getCurrentSession().getNamedQuery("ListUsers");
pStmt = sf.getCurrentSession().connection().prepareStatement(q.getQueryString());
rs = pStmt.executeQuery();// works fine till here
ret = new QueryTable(rs); // error line
rs.close();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
return ret;
Can you provide some help on this. Please let me know if you need any other details.We have found this error is logs
coldfusion.runtime.Encryptor$InvalidParamsForEncryptionException: An error occurred while trying to encrypt or decrypt your input string: The input and output encodings are not same..
at coldfusion.runtime.Encryptor.decrypt(Encryptor.java:303)
at coldfusion.runtime.Encryptor.decrypt(Encryptor.java:284)
at coldfusion.runtime.CFPage.Decrypt(CFPage.java:5353)
at coldfusion.runtime.CFPage.Decrypt(CFPage.java:5326)
at coldfusion.runtime.CFPage.Decrypt(CFPage.java:5458)
at com.vmware.vcp.service.impl.EncryptColdFusionImpl.decrypt(EncryptColdFusionImpl.java:65)
at com.vmware.vcp.web.servlet.ApplicationConfigServlet.initEmailService(ApplicationConfigSer vlet.java:119)
at com.vmware.vcp.web.servlet.ApplicationConfigServlet.init(ApplicationConfigServlet.java:51 )
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at coldfusion.bootstrap.ClassloaderHelper.initServletClass(ClassloaderHelper.java:121)
at coldfusion.bootstrap.BootstrapServlet.init(BootstrapServlet.java:59)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5001)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5278)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722) -
Help :add multiple rows from Resultset to ArrayList ?
My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
ex:
item_num
p001
p002
p003
when I print, it only gets the item in the first row.
ArrayList myArrayList = new ArrayList();
resultset = preparedstatement.executeQuery();
if (resultset.next())
myArrayList.add(new String(resultset.getString("item_num")));
Print:
for (int j = 0 ; j < myArrayList.size() ; j++ )
System.out.println((String)myArrayList.get(j)); --this prints only the first item.
can someone assist ?changing if to while fixed it.
-
How to get resultset from procedure having dynamic select sql query ?
Hi,
I have created a procedure, in which there is dynamic select query. The procedure has one out put parameter which gives error code. When I compile that procedure it compiles successufully. When I run it it executes successfully and gives output error code. But I don't know how to get resultset of that dynamic select sql query. I need that.
This is the procedure:
create or replace
PROCEDURE uspGetProductDetailsMultiOrder
v_DefinitionDBName IN VARCHAR2,
v_CommonDBName IN VARCHAR2,
v_Filter_FilledStatus IN VARCHAR2,
v_Filter_Internal_Counterparty IN nvarchar2,
v_Filter_NoteType IN nvarchar2,
v_Filter_Exchange IN nvarchar2,
v_Filter_Issuer IN nvarchar2,
v_Filter_Product_Category IN VARCHAR2,
v_DateToFilter IN VARCHAR2,
v_Filter_FromDate IN VARCHAR2,
v_Filter_ToDate IN VARCHAR2,
v_Active_YN_Flag IN NVARCHAR2,
v_Entity_ID IN NVARCHAR2,
v_ErrorNumber OUT NUMBER
as
v_SelectSQL nvarchar2(32767);
v_Setting_Name nvarchar2(32767);
v_Default_Value nvarchar2(32767);
v_Config_Value nvarchar2(32767);
v_CCY_ID NUMBER(10,0);
v_CCY_Data nvarchar2(32767);
v_CCY_List nvarchar2(32767);
v_Seq_Id NUMBER(10,0);
SWV_Active_YN_Flag NVARCHAR2(1);
SWV_VarStr long;--varchar2(4000);
SWV_TRANCOUNT NUMBER(10,0);
SWV_fnc_SplitString_Id_var1 NUMBER(10,0);
SWV_fnc_SplitString_Id_var0 NUMBER(10,0);
CURSOR RestrictTermsheetVisibilityByC
IS select CS.Setting_Name,Default_Value,Config_Value
from Config_Settings CS LEFT OUTER JOIN Entity_Config EC ON EC.Setting_ID = CS.Setting_ID
where EC.Entity_ID = v_Entity_ID AND Setting_Level = 'ENTITY';
CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,','));
--CURSOR Get_RestrictCCY_List_Cursor IS SELECT Id,Data FROM imp;
CURSOR GetRestrictTemplateListCursor
-- is select id,data from imp;
IS SELECT Id_1,Data_1 FROM table(fnc_SplitString(v_Config_Value,',')) ;
--Parikshit 18-Jul-2010, active YN flag param added in SP
BEGIN
SWV_Active_YN_Flag := v_Active_YN_Flag;
if SWV_Active_YN_Flag = ' ' then
SWV_Active_YN_Flag := 'Y';
end if;
v_SelectSQL := ' ';
v_SelectSQL := v_SelectSQL || ' Select ';
v_SelectSQL := v_SelectSQL || ' NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency';
--SET @SelectSQL = @SelectSQL + ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.Type like '' ELN%'' or NM.Type like ''RELN%'') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost '
v_SelectSQL := v_SelectSQL || ' , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = ''Y'') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = ''Y'') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost ';
v_SelectSQL := v_SelectSQL || ' , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount, NM.Active_YN_Flag, NM.Verify_YN_Flag ';
v_SelectSQL := v_SelectSQL || ' , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At, NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer';
v_SelectSQL := v_SelectSQL || ' , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount ';
--Added by Parikshit on 14-Jun-2011, to remove the unwinding amounts from the total issue size
--SET @SelectSQL = @SelectSQL + ' , NOP.LastTimeWhenProductModified,NOP.Nominal_Amount as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty '
v_SelectSQL := v_SelectSQL || ' , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty ';
--********************************************************END
v_SelectSQL := v_SelectSQL || ' ,T2.Confirmed_Amount, T2.Confirmed_Shares';
v_SelectSQL := v_SelectSQL || ' , T3.Live_Deals';
v_SelectSQL := v_SelectSQL || ' , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL ';
v_SelectSQL := v_SelectSQL || ' , ( case When UPPER(NM.PreHedged_YN) = ''Y'' Then ''Launched'' ';
v_SelectSQL := v_SelectSQL || ' When ((NM.Maturity_Date IS NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then ''Matured''';
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NOT NULL) Then ''Launched''';
--Ready to launch
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND to_date(Close_Date) > to_date(sysdate) ) Then ''Ready To Launch''';
--Ready to launch
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)= to_date(sysdate) ) Then ''Ready To Launch''';
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)< to_date(sysdate) ) Then ''Ready To Launch''';
--Warning trigger reached
v_SelectSQL := v_SelectSQL || ' When (UPPER(NM.PreHedged_YN) = ''N'' AND NM.Launch_Date IS NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning )) Then ''Warning Trigger Reached''';
v_SelectSQL := v_SelectSQL || ' Else ''Not Ready'' ';
v_SelectSQL := v_SelectSQL || ' End)Launch_Status';
v_SelectSQL := v_SelectSQL || ' , NI.Issuer_Code';
v_SelectSQL := v_SelectSQL || ' , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront, case when UPPER(NM.PreHedged_YN) = ''Y'' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge';
v_SelectSQL := v_SelectSQL || ' , NOP.Hard_Margin as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class ';
v_SelectSQL := v_SelectSQL || ' , NM.Note_Product_Rating as Product_Rating, NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count, nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID, ( (case when NM.Note_Order_Type = '''' then N''Market'' else NM.Note_Order_Type end ) ) as Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,''Atmaturity'') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,''N'') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
Note_Premium_PC ';
v_SelectSQL := v_SelectSQL || ' , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, ''Product'' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
NM.NM_Counterparty_Upfront, NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate ';
v_SelectSQL := v_SelectSQL || ' from ';
v_SelectSQL := v_SelectSQL || v_CommonDBName|| '.Note_Master NM ';
v_SelectSQL := v_SelectSQL || 'Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Master NI ';
v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (NI.Issuer_Name as nvarchar2(25)) else cast(NI.Issuer_Id as nvarchar2(25)) end )';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Order_Product NOP ';
v_SelectSQL := v_SelectSQL || ' On NOP.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_DefinitionDBName||'.AssetDef AD ';
v_SelectSQL := v_SelectSQL || ' On AD.Code = NM.Asset';
v_SelectSQL := v_SelectSQL || ' AND AD.TypeAsset = substr(NM.Note_Asset_Class,1,2) ';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Issuer_Parameter IP ';
v_SelectSQL := v_SelectSQL || ' On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (IP.Issuer_Name as nvarchar2(25)) else cast(IP.Issuer_Id as nvarchar2(25)) end )';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Template_Master TM ';
v_SelectSQL := v_SelectSQL || ' On TM.Template_Id = NM.Template_ID ';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Scheme_Codes SC ';
v_SelectSQL := v_SelectSQL || ' On SC.Scheme_Alias = NM.Type';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Counterparty_Master CM ';
v_SelectSQL := v_SelectSQL || ' On CM.CM_ID = NM.Counterparty';
v_SelectSQL := v_SelectSQL || ' Left Outer Join ';
v_SelectSQL := v_SelectSQL || ' ( ';
v_SelectSQL := v_SelectSQL || ' Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from ';
v_SelectSQL := v_SelectSQL || v_CommonDBName||'.Note_Deals ';
v_SelectSQL := v_SelectSQL || ' where Prematurity_Date IS NOT NULL';
v_SelectSQL := v_SelectSQL || ' AND (UPPER(Deletion_Reason ) = ''PART REDEMPTION'' or UPPER(Deletion_Reason ) = ''FULL REDEMPTION'')';
v_SelectSQL := v_SelectSQL || ' Group by Note_master_ID ';
v_SelectSQL := v_SelectSQL || ' ) ND ';
v_SelectSQL := v_SelectSQL || ' On ND.Note_Master_ID = NM.Note_Master_ID';
if (v_Filter_FilledStatus = ' ' OR UPPER(v_Filter_FilledStatus) = 'ALL' ) then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NOP.Filled_Status IN (' || v_Filter_FilledStatus || ')';
end if;
--AND NOP.Internal_Counterparty = 'DEFAULT''
if(SUBSTR(to_char(v_Filter_Internal_Counterparty),1,4000)= ' ') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NOP.Internal_Counterparty IN (' || v_Filter_Internal_Counterparty || ')';
end if;
--SET @SelectSQL = @SelectSQL + ' --Filter--'
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN ';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares) As Confirmed_Shares ';
v_SelectSQL := v_SelectSQL || ' from '||v_CommonDBName||'.Note_Order_RM ';
v_SelectSQL := v_SelectSQL || ' Where substr(UPPER(Order_Status_Flag),1,6) = ''YYYYYY'' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = ''N'' ';
v_SelectSQL := v_SelectSQL || ' group by Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) T2';
v_SelectSQL := v_SelectSQL || ' ON T2.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals ';
v_SelectSQL := v_SelectSQL || ' from '||v_CommonDBName||'.Note_Deals ND ';
v_SelectSQL := v_SelectSQL || ' where ND.Active_YNFlag = ''Y'' ';
v_SelectSQL := v_SelectSQL || ' group by Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) T3';
v_SelectSQL := v_SelectSQL || ' ON T3.Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' LEFT OUTER JOIN';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT)) Net_Trade_Hedged,';
v_SelectSQL := v_SelectSQL || ' (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT)) Net_Trade_Outstanding,';
v_SelectSQL := v_SelectSQL || ' SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY,';
v_SelectSQL := v_SelectSQL || ' SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY,';
v_SelectSQL := v_SelectSQL || ' SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' From';
v_SelectSQL := v_SelectSQL || ' (';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' FROM '||v_CommonDBName||'.Note_Hedge ';
v_SelectSQL := v_SelectSQL || ' WHERE NH_Direction = ''BUY'' ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Union';
v_SelectSQL := v_SelectSQL || ' SELECT NH_Note_Master_ID,';
v_SelectSQL := v_SelectSQL || ' 0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL,';
v_SelectSQL := v_SelectSQL || ' 0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL';
v_SelectSQL := v_SelectSQL || ' FROM '||v_CommonDBName||'.Note_Hedge ';
v_SelectSQL := v_SelectSQL || ' WHERE NH_Direction = ''SELL'' ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) ';
v_SelectSQL := v_SelectSQL || ' GROUP BY NH_Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' ) BS';
v_SelectSQL := v_SelectSQL || ' ON BS.NH_Note_Master_ID = NM.Note_Master_ID';
v_SelectSQL := v_SelectSQL || ' Where NM.Verify_YN_Flag = ''Y'' ';
v_SelectSQL := v_SelectSQL || ' AND NM.Active_YN_Flag = ''' || SWV_Active_YN_Flag || '''';
if(SUBSTR(to_char(v_Filter_NoteType),1,4000) = ' ' OR UPPER(v_Filter_NoteType) = 'ALL' ) then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Type IN (' || v_Filter_NoteType || ')';
end if;
IF UPPER(v_Entity_ID) <> 'ALL' then
OPEN RestrictTermsheetVisibilityByC;
FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
WHILE RestrictTermsheetVisibilityByC%FOUND LOOP
--2) Convert comma separated ccy (CNY,HKD,USD) string to single quote ccy with comma separated Ccy ('CNY','HKD','USD') string
if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_CCY') then
if v_Config_Value is not null then
SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var0 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
IF (SWV_fnc_SplitString_Id_var0 > 0) then
--print 'Before Single quote separated ccy : ' + '''' + @Config_Value + ''''
v_Seq_Id := 0;
OPEN Get_RestrictCCY_List_Cursor;
FETCH Get_RestrictCCY_List_Cursor
INTO v_CCY_ID,v_CCY_Data;
WHILE Get_RestrictCCY_List_Cursor%FOUND LOOP
if v_Seq_Id = 0 then
v_CCY_List := '''' || v_CCY_Data || '''';
else
v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
end if;
v_Seq_Id := v_Seq_Id+1;
FETCH Get_RestrictCCY_List_Cursor INTO v_CCY_ID,v_CCY_Data;
END LOOP;
CLOSE Get_RestrictCCY_List_Cursor;
--print 'After Single quote ccy : ' + @CCY_List
v_SelectSQL := v_SelectSQL || ' AND nvl(NM.Denomination_Ccy,NM.Currency) NOT IN (' || v_CCY_List || ')';
end if;
end if;
end if;
--3) Convert comma separated template (ELN,BELN,BELN_B) string to single quote template code with comma separated template ('ELN','BELN','BELN_B') string
if (UPPER(v_Setting_Name) = 'RESTRICT_TERMSHEET_VISIBILITY_BY_SUBSCHEME') then
if v_Config_Value is not null then
SELECT COUNT(Id_1) INTO SWV_fnc_SplitString_Id_var1 FROM TABLE(fnc_SplitString(v_Config_Value,',')) ;
IF (SWV_fnc_SplitString_Id_var1 > 0) then
v_Seq_Id := 0;
OPEN GetRestrictTemplateListCursor;
FETCH GetRestrictTemplateListCursor
INTO v_CCY_ID,v_CCY_Data;
WHILE GetRestrictTemplateListCursor%FOUND
LOOP
if v_Seq_Id = 0 then
v_CCY_List := '''' || v_CCY_Data || '''';
else
v_CCY_List := v_CCY_List || ',' || '''' || v_CCY_Data || '''';
end if;
v_Seq_Id := v_Seq_Id+1;
FETCH GetRestrictTemplateListCursor INTO v_CCY_ID,v_CCY_Data;
END LOOP;
CLOSE GetRestrictTemplateListCursor;
--print 'After Single quote template code: ' + @CCY_List
v_SelectSQL := v_SelectSQL || ' AND TM.Template_Code NOT IN (' || v_CCY_List || ')';
end if;
end if;
end if;
FETCH RestrictTermsheetVisibilityByC INTO v_Setting_Name,v_Default_Value,v_Config_Value;
END LOOP;
CLOSE RestrictTermsheetVisibilityByC;
end if;
if (v_Filter_Exchange = ' ' OR UPPER(v_Filter_Exchange) = 'ALL') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Exchange IN (' || v_Filter_Exchange || ')';
end if;
--SET @SelectSQL = @SelectSQL + ' --AND NM.Issuer = 4'
if (v_Filter_Issuer = ' ' OR UPPER(v_Filter_Issuer) = 'ALL') then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND NM.Issuer IN (' || v_Filter_Issuer || ')';
end if;
if v_Filter_Product_Category = ' ' then
v_SelectSQL := v_SelectSQL || ' ';
else
v_SelectSQL := v_SelectSQL || ' AND UPPER(NM.Note_Issuer_Type) IN (''' || v_Filter_Product_Category || ''')';
end if;
if UPPER(v_DateToFilter) = 'NA' then
v_SelectSQL := v_SelectSQL || ' ';
else
if UPPER(v_DateToFilter) = 'CLOSE_DATE' then
v_SelectSQL := v_SelectSQL || ' AND to_char( '|| v_DateToFilter || ') >= to_date(''' || v_Filter_ToDate || ''');
-- AND convert(smalldatetime,''' || v_Filter_ToDate || ''',106) ';
else
v_SelectSQL := v_SelectSQL || ' AND to_char(''' || v_DateToFilter || ''') BETWEEN to_date(''' || v_Filter_FromDate || ''') AND to_date(''' || v_Filter_ToDate || ''') ';
end if;
end if;
v_SelectSQL := v_SelectSQL || ' Order by NM.Product_Name';
SWV_VarStr := v_SelectSQL;
DBMS_OUTPUT.PUT_LINE(SWV_VarStr);
EXECUTE IMMEDIATE SWV_VarStr;
IF SQLCODE <> 0 then
GOTO ERROR_HANDLER;
end if;
IF SQL%rowcount > 0 then
COMMIT;
SWV_TRANCOUNT := SWV_TRANCOUNT -1;
end if; --Commit Transaction
v_ErrorNumber := SQLCODE;
RETURN;
<< ERROR_HANDLER >> v_ErrorNumber := SQLCODE;
ROLLBACK;
SWV_TRANCOUNT := 0; --Rollback Transaction
RETURN;
END;Please suggest something. Thanks
Edited by: BluShadow on 30-Nov-2011 11:00
added {noformat}{noformat} tags for formatting of code. Please read {message:id=9360002} to learn to do this yourself in future.Connecting to the database sample_adf_finiq_common.
Select NM.Note_Master_Id, NM.Product_Name, NM.Template_ID, NM.Template_Sr_No, NM.Asset, NM.Exchange, NM.Type, NM.Currency , NM.Trade_Date, NM.Value_Date, NM.Valuation_Date, NM.Maturity_Date, NM.Tenor, NM.Strike_Price_Percentage, (case when (NM.PriceList_YN = 'Y') THEN NOP.Issue_Price Else NM.Customer_Price End) as Customer_Price, NM.Dealer_Price, (case when (NM.PriceList_YN = 'Y') THEN NOP.Customer_Yield Else NM.Customer_Yield End) as Customer_Yield, NOP.Dealer_Cost_PA as Internal_Cost , NM.Minimum_Issue_Size, NM.Maximum_Issue_Size, NM.Minimum_Tolerence_Amount, NM.Maximum_Tolerence_Amount, NM.Trigger_Amount_Warning, nvl(NM.PerUnit_Equivalent_Amount,1) as PerUnit_Equivalent_Amount, NM.Active_YN_Flag, NM.Verify_YN_Flag , NM.Tranche_YN_Flag, NM.Launch_Date, NM.Open_Date, NM.Close_Date, NM.PreHedged_YN, NM.Created_By, NM.Created_At, NM.Verified_At, NM.Verified_By, NM.ISIN, NM.Issuer , NM.Product_Catagory as Product_Category, NM.Note_Issuer_Type as Issuer_Category, NM.Series_No as Series_No, NM.Minimum_Investment_Amount , NOP.LastTimeWhenProductModified,(NOP.Nominal_Amount - nvl(ND.Unwind_Amount,0) ) as Current_Issue_Size, NOP.Filled_Status, NM.Counterparty as Internal_Counterparty ,T2.Confirmed_Amount, T2.Confirmed_Shares , T3.Live_Deals , BS.Net_Trade_Hedged, BS.Net_Trade_Outstanding, BS.Hedged_Nominal_BUY, BS.Hedged_Nominal_SELL, BS.Outstanding_Nominal_BUY, BS.Outstanding_Nominal_SELL , ( case When UPPER(NM.PreHedged_YN) = 'Y' Then 'Launched' When ((NM.Maturity_Date IS NOT NULL) AND to_date(NM.Maturity_Date) <= to_date(sysdate)) Then 'Matured' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL) Then 'Launched' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= NM.Minimum_Issue_Size) AND to_date(Close_Date) > to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)= to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NULL AND (T2.Confirmed_Amount >= (NM.Minimum_Issue_Size - NM.Minimum_Tolerence_Amount)) AND to_date(Close_Date)< to_date(sysdate) ) Then 'Ready To Launch' When (UPPER(NM.PreHedged_YN) = 'N' AND NM.Launch_Date IS NOT NULL AND (T2.Confirmed_Amount >= NM.Trigger_Amount_Warning )) Then 'Warning Trigger Reached' Else 'Not Ready' End)Launch_Status , NI.Issuer_Code , (nvl(NOP.Nominal_Amount,0) - nvl(T2.Confirmed_Amount,0)) as Unconfirmed_Amount, NM.Upfront as Upfront, case when UPPER(NM.PreHedged_YN) = 'Y' THEN 0 else (nvl(T2.Confirmed_Amount,0) - nvl(BS.Net_Trade_Hedged,0)) end as ReadyToHedge , NOP.Hard_Margin as Margin_Amount, NM.YearBasis as YearBasis, NM.Note_Product_Rating as Equity_Risk_Score, AD.Equity_Asset_Class , NM.Note_Product_Rating as Product_Rating, NOP.PO_ID, AD.LotSize as Lot_Size, NM.Max_Orders_Per_Product as MAX_Orders, NOP.Order_Count as Current_Order_Count, nvl(NM.Denomination_Ccy,NM.Currency) as Denomination_Ccy, NM.Note_Scheme_Type as Underlying_Type, NM.Note_Asset_Class as Asset_Class, NULL as Product_Created_YN, NULL as Product_Created_ID, ( (case when NM.Note_Order_Type = '' then N'Market' else NM.Note_Order_Type end ) ) as Order_Type, NOP.Spot_Price, NM.Note_Price_Link, NOP.Strike_Price, NVL(NM.C_Fixing_Frequency,'Atmaturity') as Fixing_Frequency, NM.Document_Uploaded_YN, NM.Document_Uploaded_At, NM.Document_Uploaded_By, NM.Document_File_Name, NM.Document_File_Extension, NM.Document_File_Path, NM.CutOff_Time, NM.Soft_Tenor, NM.NM_Sn_Code_All, NULL as Note_Price_Source, AD.LongName, NVL(NM.Pricelist_YN,'N') as Pricelist_YN, AD.AlternateIdentifierAlias as Underlying, NM.Note_Issuer_Date_Offset, NM.Counterparty as Note_Counter_Party, NULL as
Note_Premium_PC , NI.Issuer_Name, IP.Issuer_Id, IP.Broad_Cash, IP.Odd_Cash, IP.Account_Note, IP.Rounding, IP.Decimal_Truncate, IP.Misc1 as Recidual_YN, NM.Note_Issuer_Type, NM.Target_Coupon, C_Fixing_Frequency as C_Fixing_Frequency, NM.Callable_Frequency as Callable_Frequency, NM.Strike_Price_Percentage as C_Note_Strike_PC, NM.NM_Airbag_PC as Airbag_PC, C_Note_Barrier_PC as C_Note_Barrier_PC, TM.Template_Name, 'Product' as Record_Type, NM.C_Settlement_Frequency, NM.Coupon_Frequency, NM.NM_Fixing_Source as Note_Fixing_Source, NM.Order_Entry_Type, (nvl(NM.Minimum_Issue_Size,0) - nvl(T2.Confirmed_Amount,0)) as Remaining_Launch_Amount, NM.C_Fixing_Start_Point, NM.C_Fixing_End_Point, NM.Order_Entry_Type, SC.Scheme_Alias, SC.Scheme_Name, CM.CM_ID, CM.CM_Name as Counterparty_Name, NM.NM_Other_Features as Other_Features, NM.Strike_Price_Percentage as Accrual_Strike, NM.NM_KnockIn as KnockIn, NM.NM_Airbag_Type, NM.NM_Put_strike as Put_Strike, NM.NM_Accrual_Strike,
NM.NM_Counterparty_Upfront, NM.Price_Updated_YN as Prices_Updated_YN, AD.Code as Asset_Name,NULL as KO_FREQ_TYPE, NM.Daily_Accumalation_Equities, NM.MaxNoAcc_days, NM.Guaranteed_Days, NM.Leverage_ratio, NM.NORM_IF, NM.NORM_PAIR, NM.NORM_FXRate from Sample_ADF_finiq_Common.Note_Master NM Left Outer Join Sample_ADF_finiq_Common.Issuer_Master NI On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (NI.Issuer_Name as nvarchar2(25)) else cast(NI.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Note_Order_Product NOP On NOP.Note_Master_ID = NM.Note_Master_ID Left Outer Join Sample_ADF_finiq_Common.AssetDef AD On AD.Code = NM.Asset AND AD.TypeAsset = substr(NM.Note_Asset_Class,1,2) Left Outer Join Sample_ADF_finiq_Common.Issuer_Parameter IP On NM.Issuer = (case when ISNUMERIC(NM.Issuer) = 0 then cast (IP.Issuer_Name as nvarchar2(25)) else cast(IP.Issuer_Id as nvarchar2(25)) end ) Left Outer Join Sample_ADF_finiq_Common.Template_Master TM On TM.Template_Id = NM.Template_ID Left Outer Join Sample_ADF_finiq_Common.Scheme_Codes SC On SC.Scheme_Alias = NM.Type Left Outer Join Sample_ADF_finiq_Common.Counterparty_Master CM On CM.CM_ID = NM.Counterparty Left Outer Join ( Select Note_master_ID, sum(Nominal_Amt) as Unwind_Amount from Sample_ADF_finiq_Common.Note_Deals where Prematurity_Date IS NOT NULL AND (UPPER(Deletion_Reason ) = 'PART REDEMPTION' or UPPER(Deletion_Reason ) = 'FULL REDEMPTION') Group by Note_master_ID ) ND On ND.Note_Master_ID = NM.Note_Master_ID AND NOP.Internal_Counterparty IN (1) LEFT OUTER JOIN ( select Note_Master_ID, sum(Nominal_Amount) As Confirmed_Amount, sum(No_Of_Shares) As Confirmed_Shares from Sample_ADF_finiq_Common.Note_Order_RM Where substr(UPPER(Order_Status_Flag),1,6) = 'YYYYYY' AND substr(substr(UPPER(Order_Status_Flag),1,7),-1,1) = 'N' group by Note_Master_ID ) T2 ON T2.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( Select ND.Note_Master_ID, sum(ND.Nominal_Amt) As Live_Deals from Sample_ADF_finiq_Common.Note_Deals ND where ND.Active_YNFlag = 'Y' group by Note_Master_ID ) T3 ON T3.Note_Master_ID = NM.Note_Master_ID LEFT OUTER JOIN ( SELECT NH_Note_Master_ID, (CAST(SUM(Hedged_Nominal_Buy) AS BINARY_FLOAT) -CAST(SUM(Hedged_Nominal_Sell) AS BINARY_FLOAT)) Net_Trade_Hedged, (CAST(SUM(Outstanding_Nominal_BUY) AS BINARY_FLOAT) -CAST(SUM(Outstanding_Nominal_SELL) AS BINARY_FLOAT)) Net_Trade_Outstanding, SUM(Hedged_Nominal_BUY) AS Hedged_Nominal_BUY, SUM(Hedged_Nominal_SELL) AS Hedged_Nominal_SELL, SUM(Outstanding_Nominal_BUY) AS Outstanding_Nominal_BUY, SUM(Outstanding_Nominal_SELL) As Outstanding_Nominal_SELL From ( SELECT NH_Note_Master_ID, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_BUY, 0 AS Hedged_Nominal_SELL, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_BUY, 0 AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'BUY' GROUP BY NH_Note_Master_ID Union SELECT NH_Note_Master_ID, 0 AS Hedged_Nominal_BUY, SUM(NH_Hedged_Nominal) AS Hedged_Nominal_SELL, 0 AS Outstanding_Nominal_BUY, SUM(NH_Outstanding_Nominal) AS Outstanding_Nominal_SELL FROM Sample_ADF_finiq_Common.Note_Hedge WHERE NH_Direction = 'SELL' GROUP BY NH_Note_Master_ID ) GROUP BY NH_Note_Master_ID ) BS ON BS.NH_Note_Master_ID = NM.Note_Master_ID Where NM.Verify_YN_Flag = 'Y' AND NM.Active_YN_Flag = 'Y' AND UPPER(NM.Note_Issuer_Type) IN ('Internal') AND to_char('16-oct-11') BETWEEN to_date('15-oct-11') AND to_date('17-oct-11') Order by NM.Product_Name
V_ERRORNUMBER = 0
Process exited.
Disconnecting from the database sample_adf_finiq_common.
here v_errornumber=0 is the output when i run it in oracle sql developer. -
Two different Resultsets for the same query (running at the same time)
I am using the Thin Driver for Oracle 8.1.6. I am invoking queries in multithreading mode (each thread has his own connection to the oracle DB). If i am invoking the same SQL-Statement in two different threads nearly at the same time, only the ResultSet of the first query is complete. The ResultSet of the second query is not complete (the number of tuples differs each time I run the program). Principally the two ResultSets should be the same (no changes are done at the same time in the DB), but they are not.
Anybody knows this problem and knows how to solve it? Principally read accesses on DBs should not make such trouble ...
I hope anybody can help me.Pranav,
As this BADI is having option checked 'Multiple use'. You can implement multiple implementations.
You need not to deactivate the existing implementation.
Reddy -
Closing Statements and ResultSets
I just recently realized that you need to close Statements and ResultSets in order to avoid getting the "Too many cursors"-message.
My question is:
Do you need to close both Statements and ResultSets?
- not that it's a problem...
if so:
Does it matter which one you close first?I usually place the stmt.close() code in my finally block, to ensure that the statement gets closed, even if a SQLException occurs during the query/update. The ResultSet does not explicitly have to be closed, ... it is automatically closed when the Statement is closed, or if a new query is run on the same statement.
-
Closing PreparedStatements & ResultSets
Is it necessary to explicitly close ResultSet AND PreparedStatement objects when used together? For example:
PreparedStatement ps;
ResultSet rs;
String sql = " SELECT * FROM some_table WHERE id = ? ";
try {
ps = connection.prepareStatement(sql);
ps.setString(1, someId);
rs = ps.executeQuery();
// And so on.....
} finally {
rs.close();
ps.close();
}Is it sufficient to close only the PreparedStatement? Does the ResultSet get cleaned up automatically when the PreparedStatement is closed? I don't want any lingering cursors left open, but at the same time, I don't want to write code that isn't needed. What's considered best form?
Thanks.
BTW: I'm using Oracle 8i/9i.I always close a Statement object, but don't worry about the ResultSet...that's really just a matter of redundancy...
From the API on Statement.close()
Note: A Statement object is automatically closed when it is garbage collected. When a Statement object is closed, its current ResultSet object, if one exists, is also closed. -
ResultSets Closing, cant use .last() etc
I am filling 3 seperate resultsets using 3 seperate sql queries.
The 1st query calls the connection classes setData() and passes in the sql statement, which connects, gets the data, puts it in a resultset, and returns it to the calling class. Then, the returned resultset copied into resultset1.
The 2nd query then does the same thing, but its sql statement is getting different data from a different table, but it still uses the getData() method to do it. It then fills resultset2.
Then the 3rd query runs its sql query the same way to fill resultset3.
The problem is, after i have filled resultsets 1, 2 and 3, it wont let me call a .first() or .last() on any of them cause it says that the resultset is closed! Heres the exact error msg:
"java.sql.SQLException: Operation not allowed after ResultSet closed"
Heres the code where i try fill the 3 resultsets:
mycon = new MysqlConnect();
details_res = mycon.getData("SELECT * FROM details ORDER BY details_id");
details_res.last();
parts_res = mycon.getData("SELECT * FROM parts ORDER BY parts_id");
parts_res.last();
costs_res = mycon.getData("SELECT * FROM costs ORDER BY costs_id");
costs_res.last();'mycon' is an object of the connection class.
So im guessing that ive got a problem in the getData() method of the connection class so heres the code for that method:
public ResultSet getData(String query)
connect();
try
// browseable in all directions, not sensitive to updates by other users, not updateable
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // create empty SQL statement
// execute SQL query & store results
result = stmt.executeQuery(query);
con.close(); // close connection
System.out.println("Data Retrieved. Connection Closed");
catch (SQLException e)
System.out.println("SQL Exception " + e);
return result; // return the data
}//end getData()'stmt' and 'con' are both declared at the top, private variables.Right. Exactly. This is the way it's supposed to be. You've got major fundamental flaws in your approach.
First, the result set is not being copied, you're creating a new reference to it.
Second, result sets AREN'T copied.
Third, a ResultSet represents an arbitrarily large flow of data that will come throw the connection as you step through elements in the ResultSet; as soon as you close the connection, you cut off the flow.
So the excpetion is exactly right, you've closed the flow and therefore can't move around in the ResultSet. -
Too many connections - even after closing ResultSets and PreparedStatements
I'm getting a "Too many connections" error with MySQL when I run my Java program.
2007-08-06 15:07:26,650 main/CLIRuntime [FATAL]: Too many connections
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670)I researched on this and found out that I wasn't closing the ResultSet and the PreparedStatement.
The JDBC connection is closed by a central program that handles connections (custom connection pooling).
I added the code to close all ResultSets and PreparedStatements, and re-started MySQL as per the instructions here
but still get "Too many connections" error.
A few other things come to mind, as to what I may be doing wrong, so I have a few questions:
1) A few PreparedStatements are created in one method, and they are used in a 2nd method and closed in the 2nd method
does this cause "Too many connections" error?
2) I have 2 different ResultSets, in nested while loops where the outer loop iterates over the first ResultSet and
the inner loop iterates over the second ResultSet.
I have a try-finally block that wraps the inner while loop, and I'm closing the second ResultSet and PreparedStement
in the inner while loop.
I also have a try-finally block that wraps the outer while loop, and I'm closing the first ResulSet and PreparedStatement
in the outer while loop as soon as the inner while loop completes.
So, in the above case the outer while loop's ResultSet and PreparedStatements remain open until the inner while loop completes.
Does the above cause "Too many connections" error?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The following is relevant sections of my code ( it is partially pseudo-code ) that shows the above 2 cases:
init( Connection jdbcConnection ){
String firstSQLStatement = "....";
PreparedStatement ps1 = jdbcConnection.prepareStatement( firstSQLStatement );
String secondSQLStatement = "....";
PreparedStatement ps2 = jdbcConnection.prepareStatement( secondSQLStatement );
String thirdSQLStatement = "....";
PreparedStatement ps3 = null;
ResultSet rsA = null;
try{
ps3 = jdbcConnection.prepareStatement( thirdSQLStatement );
rsA = ps3.executeQuery();
if( rsA.next() ){
rsA.getString( 1 );
}finally{
if( rsA != null )
rsA.close();
if( ps3 != null )
ps3.close();
//Notice, how ps1 and ps2 are created here but not used immediately, but only ps3 is
//used immediately.
//ps1 and ps2 are used in another method.
run( Connection jdbcConnection ){
ResultSet rs1 = ps1.executeQuery();
try{
while(rs1.next()){
String s = rs1.getString();
ps2.setString(1, s);
ResultSet rs2 = ps2.executeQuery();
try{
while(rs2.next()){
String s2 = rs2.getString();
}finally{
if( rs2 != null )
rs2.close();
if( ps2 != null )
ps2.close();
}catch( Exception e ){
e.printStackTrace();
}finally{
if( rs1 != null )
rs1.close();
if( ps1 != null )
ps1.close();
//Notice in the above case rs1 and ps1 are closed only after the inner
//while loop completes.
}I appreciate any help.Thanks for your reply.
I will look at the central connection pooling mechanism ( which was written by someone else) , but that is being used by many other Java programs others have written.
They are not getting this error.
An addendum to my previous note, I followed the instructions here.
http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
There's probably something else in my code that is not closing the connection.
But I just wanted to rule out the fact that opening a PreparedStatement in one method and closing it in another is not a problem.
Or, if nested ResultSet loops don't cause the problem.
I've read in a few threads taht "Too many connections" can occur for unclosed RS and PS , and not just JDBC connections. -
Unclear about closing ResultSets
Please provide clarification: The JavaDoc for ResultSets says that you don't have to explicitly close ResultSet objects since the RS will be closed when its defining Statement is closed or when the RS is garbage collected.
The Oracle JDBC Developer's Guide and Reference states (in the section titled "Closing the Result Set and Statement Objects"):
"You must explicitly close the ResultSet and Statement objects after you finish using them. This applies to all
ResultSet and Statement objects you create when using the Oracle JDBC drivers. The drivers do not have
finalizer methods; cleanup routines are performed by the close() method of the ResultSet and Statement
classes. If you do not explicitly close your ResultSet and Statement objects, serious memory leaks could
occur. You could also run out of cursors in the database."
So, does the Oracle driver operate differently than the JDBC standard in this regard?The JavaDoc for ResultSets says that you don't have to explicitly close ResultSet objects since the RS will be closed when its defining Statement is closed or when the RS is garbage collected.In Oracle JDBC, if you close the statement, then the result set is also closed, unless you obtained the result set as an OUT parameter from a stored procedure or function that returns a REF CURSOR.
However, it is definitely not prudent to wait until the result set is garbage collected, since you have no explicit control over that! Depending on your database setup, you'll typically be able to open a couple dozen statements before you start running out of database cursors.
This is even more important if you are using SQLJ: there statements are automatically managed for you, so you'll never have to worry about closing them. However, if you do not close result sets (called iterators in SQLJ), the associated statement will be kept around and stays open (again, it might be garbage collected or it might not - no guarantees). -
I have code that creates dynamic SQL statements in a loop to search for a value in a table. The Where clause is changed in each iteration of the loop until the value is found or the loop finishes. The code looks something like this:
(Sorry for the crappy formatting of the code. I tried indenting lines, but when I previewed it, it aligned everything. Damn )
/* NOTE: variables were changed to fit in this page better */
for( int i = 9; i >=0;i--) {
SelectSQL = new StringBuffer("SELECT col FROM tab WHERE ");
for( int j = 0; j <= i;j++) {
SelectSQL.append( "col" + j + "ID = " + Val[j]);
if( j != i ) { SelectSQL.append(","); }
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY );
rs = stmt.executeQuery(SelectSQL.toString());
if( rs.next() ) {
ValID = rs.getLong(1);
/* TODO: Should I be closing these in loops? */
rs.close();
stmt.close();
if( ValID > 0 ) { break; }
My question is: Do I need to close the resultset(rs) and statement(stmt) at the bottom of the loop? That does not seem very efficient to me, but I am not sure. Any advice would be greatly appriciated. Thanks for your time.declare the statement out of the loop and close it on the
end (also out of the loop) so you reuse the statement each time,
if the ResultSet is empty it closes, also if you loop through it it closes itself, when it is empty, but i recommend to close it each time you use it anyway (in the loop)
don't forget, only select statements return a resultset .. others (delete, update) don't -
New Records in database do not show up in resultset
Hi,
I have seen very little on this but I have a MS Access database that I have records in. If I change one of those records, I see the change in the resultset which I am just printing out for now using System.out.println . So I add new records manually to the database just so I am some records to test with and those records do not show up in the resultset. After doing something (not exactly sure what as I did a lot), I happen to go back and then saw the new records. So I add some more and could not see those records. I AM closing my resultsets, connections, etc. I read something where someone had the same problem and thought something was being cached which seemed reasonable to me. So I tried rebooting for the heck of it and I still see only the previous records and not the new ones.
Any ideas,
Thanks,
KarlHi Karl,
There are problems some times like the one you mentioned when you are using both manual and programatic inserts/updates/deletes.
When ever u face any such problems look out for following :
Check if all ResultSet, Statement and Connection objects are closed before exiting the code. That is normal exit and abnormal exit (due to any error/exception).
After manual insertion save and close target table.
If the problem still exists then try re-compiling your code after closing the your Access (*.mdb) database.
I hope this will work for you.
regards,
Humayun -
PreparedStatement ResultSet wrapper to auto close cursor
Hi !
Is it possible to create wrapper that will automatically close result set and prepared statements ?
I am sick of closing resultsets and preparedstatements in all my dao objects. Its all about neverending try catch and close code lines, it is all against the java garbage collector idea.
Do you have any workaround ? Or I need to use with those try catch and close.
Thanks !when u allocate object u dont need to call free nor destory when u dont need the object anymore.
on the other hand, you need to call .close() when u dont need the prepared statement anymore -
Why does JDBC keep connections open even though I close the resultsets?
I attached my program and my output. Please bear with me for the long output. My question here is why do the connections remain even though I closed the resultsets. I need to reuse my prepared statements, but don't want to keep the oracle sessions open. Is this possible? What do I need to do?
If you notice in the program, I have executed the query to find the number of open sessions 5 times.
1) After creating the connections
2) After creating the prepared statements
3) After executing them
4) After getString on the resultSets
5) After closing the resultsets.
And the sessions are still there even is Step 5 :-(
import java.sql.*;
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
public class Test {
String dburl = "jdbc:oracle:thin:@oracle92:1521:oracle92";
String query = "select s.username,s.sid ,s.logon_time, s.serial#,sql.sql_text"+
" from v$session s, v$sqltext sql where sql.address = "+
"s.sql_address and sql.hash_value = s.sql_hash_value "+
"and upper(s.username) like 'KRTEMP%'"+
" order by s.username ,s.sid ,s.serial# ,sql.piece" ;
// String query = "select s.username, s.sid ,s.logon_time, s.status from v$session s where upper(s.username) like 'KRTEMP%'";
public Test(int num) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection[] con = new Connection[num];
for(int i=0; i<num; i++) {
con[i] = DriverManager.getConnection(dburl, "krtemp", "krtemp");
executeQuery();
PreparedStatement[] ps = new PreparedStatement[num];
for(int i=0; i<num; i++) {
ps[i] = con.prepareStatement("select * from contact");
executeQuery();
ResultSet[] rs = new ResultSet[num];
for(int i=0; i<num; i++) {
rs[i] = ps[i].executeQuery();
executeQuery();
for(int i=0; i<num; i++) {
ResultSetMetaData meta = rs[i].getMetaData();
while(rs[i].next()) {
for(int j=1; j<=meta.getColumnCount(); j++) {
rs[i].getString(j);
executeQuery();
for(int i=0; i<num; i++) {
rs[i].close();
executeQuery();
private void executeQuery() throws Exception {
Connection con = DriverManager.getConnection(dburl, "krtemp", "krtemp");
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ResultSetMetaData meta = rs.getMetaData();
System.out.println("-----");
while(rs.next()) {
for(int i=1; i<=meta.getColumnCount(); i++) {
System.out.print(rs.getString(i));
System.out.print(" ");
System.out.println();
System.out.println("-----");
public static void main(String[] args) throws Exception {
Test test = new Test(5);
The output is
KRTEMP 9 2005-06-27 17:09:30.0 5436 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS WH
ERE PARAMETER ='NLS_
KRTEMP 9 2005-06-27 17:09:30.0 5436 DATE_FORMAT'
KRTEMP 34 2005-06-26 18:51:01.0 3629 rename tstore to store
KRTEMP 37 2005-06-27 17:09:25.0 4209 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 37 2005-06-27 17:09:25.0 4209 DATE_FORMAT'
KRTEMP 74 2005-06-27 17:09:26.0 17625 select appId from profile_application_tabl
e wher
KRTEMP 74 2005-06-27 17:09:26.0 17625 e appName=:1 and appVersion=:2
KRTEMP 83 2005-06-27 17:09:25.0 1771 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 83 2005-06-27 17:09:25.0 1771 DATE_FORMAT'
KRTEMP 105 2005-06-27 17:09:30.0 3296 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 105 2005-06-27 17:09:30.0 3296 DATE_FORMAT'
KRTEMP 111 2005-06-27 17:09:25.0 4878 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 111 2005-06-27 17:09:25.0 4878 DATE_FORMAT'
KRTEMP 153 2005-06-27 17:09:30.0 31065 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 153 2005-06-27 17:09:30.0 31065 DATE_FORMAT'
KRTEMP 163 2005-06-27 17:09:30.0 3205 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 163 2005-06-27 17:09:30.0 3205 DATE_FORMAT'
KRTEMP 183 2005-06-27 17:09:30.0 3465 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 183 2005-06-27 17:09:30.0 3465 DATE_FORMAT'
KRTEMP 191 2005-06-27 17:09:26.0 5438 select appId from profile_application_tabl
e wher
KRTEMP 191 2005-06-27 17:09:26.0 5438 e appName=:1 and appVersion=:2
KRTEMP 256 2005-06-27 17:09:30.0 2718 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 256 2005-06-27 17:09:30.0 2718 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 256 2005-06-27 17:09:30.0 2718 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 256 2005-06-27 17:09:30.0 2718 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 9 2005-06-27 17:09:30.0 5436 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS WH
ERE PARAMETER ='NLS_
KRTEMP 9 2005-06-27 17:09:30.0 5436 DATE_FORMAT'
KRTEMP 34 2005-06-26 18:51:01.0 3629 rename tstore to store
KRTEMP 37 2005-06-27 17:09:25.0 4209 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 37 2005-06-27 17:09:25.0 4209 DATE_FORMAT'
KRTEMP 74 2005-06-27 17:09:26.0 17625 select appId from profile_application_tabl
e wher
KRTEMP 74 2005-06-27 17:09:26.0 17625 e appName=:1 and appVersion=:2
KRTEMP 83 2005-06-27 17:09:25.0 1771 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 83 2005-06-27 17:09:25.0 1771 DATE_FORMAT'
KRTEMP 105 2005-06-27 17:09:30.0 3296 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 105 2005-06-27 17:09:30.0 3296 DATE_FORMAT'
KRTEMP 111 2005-06-27 17:09:25.0 4878 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 111 2005-06-27 17:09:25.0 4878 DATE_FORMAT'
KRTEMP 153 2005-06-27 17:09:30.0 31065 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 153 2005-06-27 17:09:30.0 31065 DATE_FORMAT'
KRTEMP 163 2005-06-27 17:09:30.0 3205 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 163 2005-06-27 17:09:30.0 3205 DATE_FORMAT'
KRTEMP 183 2005-06-27 17:09:30.0 3465 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 183 2005-06-27 17:09:30.0 3465 DATE_FORMAT'
KRTEMP 191 2005-06-27 17:09:26.0 5438 select appId from profile_application_tabl
e wher
KRTEMP 191 2005-06-27 17:09:26.0 5438 e appName=:1 and appVersion=:2
KRTEMP 232 2005-06-27 17:09:31.0 5893 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 232 2005-06-27 17:09:31.0 5893 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 232 2005-06-27 17:09:31.0 5893 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 232 2005-06-27 17:09:31.0 5893 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 34 2005-06-26 18:51:01.0 3629 rename tstore to store
KRTEMP 37 2005-06-27 17:09:25.0 4209 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 37 2005-06-27 17:09:25.0 4209 DATE_FORMAT'
KRTEMP 74 2005-06-27 17:09:26.0 17625 select appId from profile_application_tabl
e wher
KRTEMP 74 2005-06-27 17:09:26.0 17625 e appName=:1 and appVersion=:2
KRTEMP 83 2005-06-27 17:09:25.0 1771 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 83 2005-06-27 17:09:25.0 1771 DATE_FORMAT'
KRTEMP 111 2005-06-27 17:09:25.0 4878 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 111 2005-06-27 17:09:25.0 4878 DATE_FORMAT'
KRTEMP 232 2005-06-27 17:09:31.0 5893 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 232 2005-06-27 17:09:31.0 5893 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 232 2005-06-27 17:09:31.0 5893 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 232 2005-06-27 17:09:31.0 5893 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 256 2005-06-27 17:09:31.0 2783 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 256 2005-06-27 17:09:31.0 2783 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 256 2005-06-27 17:09:31.0 2783 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 256 2005-06-27 17:09:31.0 2783 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 9 2005-06-27 17:09:30.0 5436 select * from contact
KRTEMP 34 2005-06-26 18:51:01.0 3629 rename tstore to store
KRTEMP 37 2005-06-27 17:09:25.0 4209 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 37 2005-06-27 17:09:25.0 4209 DATE_FORMAT'
KRTEMP 74 2005-06-27 17:09:26.0 17625 select appId from profile_application_tabl
e wher
KRTEMP 74 2005-06-27 17:09:26.0 17625 e appName=:1 and appVersion=:2
KRTEMP 83 2005-06-27 17:09:25.0 1771 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 83 2005-06-27 17:09:25.0 1771 DATE_FORMAT'
KRTEMP 105 2005-06-27 17:09:30.0 3296 select * from contact
KRTEMP 111 2005-06-27 17:09:25.0 4878 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 111 2005-06-27 17:09:25.0 4878 DATE_FORMAT'
KRTEMP 153 2005-06-27 17:09:30.0 31065 select * from contact
KRTEMP 163 2005-06-27 17:09:30.0 3205 select * from contact
KRTEMP 173 2005-06-27 17:09:31.0 3922 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 173 2005-06-27 17:09:31.0 3922 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 173 2005-06-27 17:09:31.0 3922 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 173 2005-06-27 17:09:31.0 3922 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 183 2005-06-27 17:09:30.0 3465 select * from contact
KRTEMP 191 2005-06-27 17:09:26.0 5438 select appId from profile_application_tabl
e wher
KRTEMP 191 2005-06-27 17:09:26.0 5438 e appName=:1 and appVersion=:2
KRTEMP 232 2005-06-27 17:09:31.0 5893 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 232 2005-06-27 17:09:31.0 5893 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 232 2005-06-27 17:09:31.0 5893 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 232 2005-06-27 17:09:31.0 5893 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 256 2005-06-27 17:09:31.0 2783 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 256 2005-06-27 17:09:31.0 2783 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 256 2005-06-27 17:09:31.0 2783 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 256 2005-06-27 17:09:31.0 2783 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 9 2005-06-27 17:09:30.0 5436 select * from contact
KRTEMP 34 2005-06-26 18:51:01.0 3629 rename tstore to store
KRTEMP 37 2005-06-27 17:09:25.0 4209 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 37 2005-06-27 17:09:25.0 4209 DATE_FORMAT'
KRTEMP 74 2005-06-27 17:09:26.0 17625 select appId from profile_application_tabl
e wher
KRTEMP 74 2005-06-27 17:09:26.0 17625 e appName=:1 and appVersion=:2
KRTEMP 83 2005-06-27 17:09:25.0 1771 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS W
HERE PARAMETER ='NLS_
KRTEMP 83 2005-06-27 17:09:25.0 1771 DATE_FORMAT'
KRTEMP 105 2005-06-27 17:09:30.0 3296 select * from contact
KRTEMP 111 2005-06-27 17:09:25.0 4878 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS
WHERE PARAMETER ='NLS_
KRTEMP 111 2005-06-27 17:09:25.0 4878 DATE_FORMAT'
KRTEMP 153 2005-06-27 17:09:30.0 31065 select * from contact
KRTEMP 163 2005-06-27 17:09:30.0 3205 select * from contact
KRTEMP 183 2005-06-27 17:09:30.0 3465 select * from contact
KRTEMP 191 2005-06-27 17:09:26.0 5438 select appId from profile_application_tabl
e wher
KRTEMP 191 2005-06-27 17:09:26.0 5438 e appName=:1 and appVersion=:2
KRTEMP 204 2005-06-27 17:09:32.0 1478 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 204 2005-06-27 17:09:32.0 1478 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 204 2005-06-27 17:09:32.0 1478 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 204 2005-06-27 17:09:32.0 1478 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 232 2005-06-27 17:09:31.0 5893 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 232 2005-06-27 17:09:31.0 5893 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 232 2005-06-27 17:09:31.0 5893 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 232 2005-06-27 17:09:31.0 5893 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.piece
KRTEMP 256 2005-06-27 17:09:31.0 2783 select s.username,s.sid ,s.logon_time, s.s
erial#,sql.sql_text fr
KRTEMP 256 2005-06-27 17:09:31.0 2783 om v$session s, v$sqltext sql where sql.ad
dress = s.sql_address
KRTEMP 256 2005-06-27 17:09:31.0 2783 and sql.hash_value = s.sql_hash_value and
upper(s.username) like
KRTEMP 256 2005-06-27 17:09:31.0 2783 'KRTEMP%' order by s.username ,s.sid ,s.s
erial# ,sql.pieceWhy do the connections stay open? Because you haven't closed them.
You answered your own question: obviously closing the ResultSet is NOT the same thing as closing the connection.
When you do a query, you want to get the connection, statement, and result set, load the data from the result set into an object or data structure, and then immediately close them all again in reverse order of creation. You want to keep the scope as narrow as possible. You want to use a connection pool to keep the cost of obtaining a connection down. You should leave caching of the PreparedStatements to the JDBC driver.
%
Maybe you are looking for
-
Retrieve the complete filename picked up by file adapter
Hi all, I would like to retrieve the complete filename which is picked up by a sender file adapter. I need to know the exact filename during runtime in order to group some messages within an BPM process. No workaround (e.g. set up multiple file adapt
-
I was wondering if I need to upgrade my Mac to a newer model. I have an early 2006 iMac 1.83GHz Intel Core Duo 2GB of Ram its the 17 inch model. I have OSX 10.6.8 installed on a 250GB HDD. I was looking at the new Macs and none of them have a SuperDr
-
Windows for Mac documents are scrambled, so is background pic
I don't like Firefox 4, it scrambles my Word for Mac documents and the background on my desktop Using Mac Osx Snow Leopard OS
-
I tried opening a power point presentation on my ipad by keynote but the ppt was not opening by keynote. It given me the following message: Presentation Couldn't be imported. The document can't be opened because it contains cells outside the boundari
-
Oil paint filter: The operation could not be completed
And this is just one of the problems I am getting. I'm running Win7 64bit, photoshop cs6 (also 64bit), have an i7 2600 and 16GB of RAM and an ati 5870 card running the latest drivers (12.8) So, the operation could not be completed whenever I try to r