Tracing SQL of PreparedStatement
Hello I've made one prepared statement .
I 've even given sql to the prepared statement and can we able to print/trace what sql is going to be executed?
String sql = "INSERT INTO transaction VALUES(NULL,?," +//shopNo "?," + //itemNo "?," + //qty "?," + //size "?," + //date "?," + //description "?," + //state "?"; //Userno PreparedStatement pstmt = c.prepareStatement(sql); pstmt.setInt(1, shop); pstmt.setInt(2, itemNo); pstmt.setInt(3, qty); pstmt.setString(4, size); pstmt.setString(5, date); pstmt.setString(6, desc); pstmt.setInt(7, state); pstmt.setInt(8, User.getUserNo()); // can we do System.out.println() to get what SQL is going to be executed?
Thanks...for help
It's p6spy
Edited by: narayan_gop_mah on Sep 8, 2010 3:13 PM
Similar Messages
-
Dynmaic sql for PreparedStatement
I'm attempting to dynamically generate the where clause of a sql query.
My code looks something like:
public void myMethod (String fieldA, Map params) throws SQLException{
String sql = "select * from tableA a, tableB b where a.field = b.field and a.field = ?"
Connection con = PoolManager.getConnection();
Iterator it = params.keySet().iterator();
while(it.hasNext()){
String fieldName = (String) it.next();
sql +="and "+fieldName+" = ? ";
PreparedStatement pStmt = conn.prepareStatement(sql);
pStmt.setString(1,fieldA);
Iterator it2 = params.keySet().iterator();
for(int i=2;it2.hasNext();i++){
String fieldName = (String) it2.next();
Object value = params.get(fieldName);
if(value instanceof String){
pStmt.setString(i,(String)value);
} else if(value instanceof Integer){
pStmt.setInt(i,((Integer)value).intValue());
} else if(value instanceof java.sql.Date){
pStmt.setDate(i, (java.sql.Date)value);
ResultSet rs = pStmt.executeQuery();
I'm using resource pooling to get a connection, so that's not my problem.
The params Map has a keyset of column names paired with values which are objects of various types, for example an entry could be ("a.entryDate",java.sql.Date(2002,1,2));
If I print out my sql following my while loop, the sql looks good. If I step through the code in a debugger, I set all of the values in the preparedStatement as I expect, it bombs when the executeQuery step is performed.
The sql exception I get states an incorrect syntax near '?'
Again, the sql looks fine and ran correctly BEFORE I tried to dynamically build the where query. This is puzzling because if I print out sql statment in either case, they are identical.
Any help would really be appreciated.
ddwbtry the following:
replace
sql +="and "+fieldName+" = ? ";with
sql +=" and "+fieldName+" = ? ";note: there is an additional space at the beginning of the string. -
Tracing SQL Queries from an Application.
I read the info on here.
http://www.psoug.org/reference/traceanalyzer.html_
I have been able to use this guide to analyze traces.
I installed DBMS_SUPPORT package on my XE database. I need to know, how can I run a trace from my front-end application and get it analyzed, using trace analyzer.
I have got trace files, by using DBMS_SUpport. I have been successful in running tkprof on them.
I need to trap the values of the bind variables that are being sent by the front-end application.
Any suggestions would be welcome.
Thanks.End to End Application Tracing can identify the source of an excessive workload, such as a high load SQL statement, by client identifier, service, module, action, session, instance, or an entire database. This isolates the problem to a specific user, service, session, or application component.
Oracle provides the trcsess command-line utility that consolidates tracing information based on specific criteria.
The SQL Trace facility and TKPROF are two basic performance diagnostic tools that can help you monitor applications running against the Oracle Server.
http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/sqltrace.htm#i19083 -
Hi All,
I have an application developed in .Net. It has lots of search screens what takes lot of time to search based on some criterias. I am accessing this from my client machine. My database is located in remote location and it has UNIX OS and Oracle is 64Bit.
I want to fine tune search performance. For this I want to know which queries are fired when user click or initiate any search.
I do not access to UNIX Box from my client machine so I can not get trace file also.
Can we get list of SQL in AWR?
Which is the best way to get these SQLs?
If I get SQL then I can concentrate improving its performance.
Regards,
DanishHi Amin,
Cut from my ADDM report is as follows:
FINDING 1: 31% impact (1600 seconds)
Individual database segments responsible for significant user I/O wait were
found.
RECOMMENDATION 1: Segment Tuning, 31% benefit (1600 seconds)
ACTION: Run "Segment Advisor" on TABLE "XYZ" with
object id 195857.
RELEVANT OBJECT: database object with id 195857
ACTION: Investigate application logic involving I/O on TABLE
"XYZ" with object id 195857.
RELEVANT OBJECT: database object with id 195857
RATIONALE: The I/O usage statistics for the object are: 1 full object
scans, 8307030 physical reads, 0 physical writes and 0 direct reads.
RATIONALE: The SQL statement with SQL_ID "8dhb6vw4s2sh0" spent
significant time waiting for User I/O on the hot object.
RELEVANT OBJECT: SQL statement with SQL_ID 8dhb6vw4s2sh0
SELECT /*NESTED_TABLE_GET_REFS*/ "XYZ"."XYZ".* FROM
"XYZ"."XYZ"
SYMPTOMS THAT LED TO THE FINDING:
SYMPTOM: Wait class "User I/O" was consuming significant database time.
(46% impact [2400 seconds])
FINDING 2: 27% impact (1421 seconds)
SQL statements consuming significant database time were found.
RECOMMENDATION 1: SQL Tuning, 44% benefit (2326 seconds)
ACTION: Run SQL Tuning Advisor on the SQL statement with SQL_ID
"8dhb6vw4s2sh0".
RELEVANT OBJECT: SQL statement with SQL_ID 8dhb6vw4s2sh0 and
PLAN_HASH 3792949475
SELECT /*NESTED_TABLE_GET_REFS*/ "xyz"."xyz".* FROM
"xyz"."xyz"
Here I can not make out my sql in this report. How should I get this?
I just want that when I execute any search in my application then I want to view SQL which is executed in backend so that I can tune it.
Thanks. -
Tracing SQL statements during an ODBC reverse
I'm trying to connect to an ODBC source via the Sun JDBC/ODBC bridge driver and am not having a lot of success. I believe most of my issues are with requests for meta data (and based on the ODBC trace file, it appears that ODBC requests made by the bridge driver are not supported by the ODBC driver I am using.) The problem is that the ODBC driver vendor wants to know what SQL I am issuing that is causing the apparently unsupported ODBC calls.
Is there a way to turn on logging of the SQL issued by the Jython RKM? I have tried using p6spy, but haven't figured out how to have it log the meta data requests.Hi Jeff,
You can try to:
- start an ODI agent in verbose mode 5 and redirect its output to a log file -> >agent.bat -v=5 > log.txt
- start your custom reverse-engineering using this agent and the RKM Jython.
You should get plenty of information in that log file.
Thanks,
Julien -
I have an application that sends SQL statements to an oracle engine using odbc. Is there a way to trace the SQL statements from the unix server that the oracle engine resides on? I do not want to use the trace function in the ODBC data source administrator.
Thanks,
-AlIdebtified your connect and then set trace for session using
exec dbms_system.SET_EV(SID,SERIAL#,10046,12,'');
10046 is event name and 12 is level.
SID and serial# you will get from v$session
Cheer,
Virag Sharma
http://virag.sharma.googlepages.com/ -
PL/SQL 101 : Exception Handling
Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL. More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
Exception Handling
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. Exceptions within code within the exception block
1. Understanding Execution Blocks (part 1)
The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
Essentially an execution block is made of 3 sections...
+---------------------------+
| Declaration Section |
+---------------------------+
| Statements Section |
+---------------------------+
| Exception Section |
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory section)
The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it. When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section. Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
3. Exceptions
Exceptions generally happen during the execution of statements in the Statements section. When an exception happens the execution of statements jumps immediately into the exception section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
(Note: The exception section still has access to all the declared items in the declaration section)
3.i) Handle the exception
We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
Example...
(without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9 exception
10 when no_data_found then
11 dbms_output.put_line('There is no employee with this employee number.');
12* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.
3.ii) Raise the exception
We do this when:-
a) we recognise the exception, handle it but still want to let the calling code know that it happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16* end;
SQL> /
Enter value for empno: 123
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16 WHEN others THEN
17 RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 'ABC';
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
4. Understanding Execution Blocks (part 2)
Ok, so now we understand the very basics of an execution block and what happens when an exception happens. Let's take it a step further...
Execution blocks are not just a single simple block in most cases. Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function. Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
+---------------------------------+
| Declaration Section |
+---------------------------------+
| Statements Section |
| . |
| +---------------------------+ |
| | Declaration Section | |
| +---------------------------+ |
| | Statements Section | |
| +---------------------------+ |
| | Exception Section | |
| +---------------------------+ |
| . |
+---------------------------------+
| Exception Section |
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)
SQL> create or replace procedure a as
2 v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure A''s Statement Section');
5 v_dummy := 1/0; -- cause an exception
6 exception
7 when others then
8 v_dummy := log_trace('Procedure A''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 a; -- HERE the execution passes to the declare/statement/exception sections of A
6 exception
7 when others then
8 v_dummy := log_trace('Procedure B''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section
Procedure A's Exception Section
Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code. However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 -- Here we start another execution block nested in the first one...
6 declare
7 v_dummy NUMBER := log_trace('Nested Block Declaration Section');
8 begin
9 v_dummy := log_trace('Nested Block Statement Section');
10 select empno
11 into v_dummy
12 from emp
13 where empno = p_empno; -- Note: the parameters and variables from
parent execution block are available to use!
14 exception
15 when no_data_found then
16 -- This is an exception we can handle so we don't raise it
17 v_dummy := log_trace('No employee was found');
18 v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
19 when others then
20 -- Other exceptions we can't handle so we raise them
21 v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
22 raise;
23 end;
24 -- ...Here endeth the nested execution block
25 -- As the nested block handled it's exception we come back to here...
26 v_dummy := log_trace('Procedure B''s Statement Section Continued');
27 exception
28 when others then
29 -- We'll only get to here if an unhandled exception was raised
30 -- either in the nested block or in procedure b's statement section
31 v_dummy := log_trace('Procedure B''s Exception Section');
32 raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued
7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>
You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
6. User defined exceptions
There are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section. The third is raising your own exception messages with our own exception numbers. Let's look at the first one...
Let's say I have tables which detail stock availablility and reorder levels...
SQL> select * from reorder_level;
ITEM_ID STOCK_LEVEL
1 20
2 20
3 10
4 2
5 2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
1 Pencils 10
2 Pens 2
3 Notepads 25
4 Stapler 5
5 Hole Punch 3
SQL>
Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item. As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 begin
11 OPEN cur_stock_reorder;
12 FETCH cur_stock_reorder INTO v_stock;
13 IF cur_stock_reorder%NOTFOUND THEN
14 RAISE no_data_found;
15 END IF;
16 CLOSE cur_stock_reorder;
17 --
18 IF v_stock.stock_level >= v_stock.reorder_level THEN
19 -- Stock is not low enough to warrant an order
20 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
21 ELSE
22 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
23 -- Required amount is over-ordering
24 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
25 ELSE
26 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27 -- Here goes our code to print the order
28 END IF;
29 END IF;
30 --
31 exception
32 WHEN no_data_found THEN
33 CLOSE cur_stock_reorder;
34 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 --
11 -- Let's declare our own exceptions for business logic...
12 exc_not_warranted EXCEPTION;
13 exc_too_much EXCEPTION;
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 RAISE exc_not_warranted;
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29 RAISE exc_too_much;
30 END IF;
31 --
32 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33 -- Here goes our code to print the order
34 --
35 exception
36 WHEN no_data_found THEN
37 CLOSE cur_stock_reorder;
38 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39 WHEN exc_not_warranted THEN
40 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
41 WHEN exc_too_much THEN
42 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
That's better. And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
Now for the second sort of user defined exception...
A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 begin
16 OPEN cur_stock_reorder;
17 FETCH cur_stock_reorder INTO v_stock;
18 IF cur_stock_reorder%NOTFOUND THEN
19 RAISE no_data_found;
20 END IF;
21 CLOSE cur_stock_reorder;
22 --
23 IF v_stock.stock_level >= v_stock.reorder_level THEN
24 -- Stock is not low enough to warrant an order
25 RAISE exc_not_warranted;
26 END IF;
27 --
28 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29 -- Required amount is over-ordering
30 RAISE exc_too_much;
31 END IF;
32 --
33 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34 -- Here goes our code to print the order, passing the finance_factor
35 --
36 exception
37 WHEN no_data_found THEN
38 CLOSE cur_stock_reorder;
39 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40 WHEN exc_not_warranted THEN
41 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
42 WHEN exc_too_much THEN
43 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-06512: at line 1
SQL>
Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an unhandled exception.
Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
EXCEPTION
WHEN ORA-01476 THEN
... is not valid. What we need is to give this Oracle error a name.
This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 --
16 exc_zero_quantity EXCEPTION;
17 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19 OPEN cur_stock_reorder;
20 FETCH cur_stock_reorder INTO v_stock;
21 IF cur_stock_reorder%NOTFOUND THEN
22 RAISE no_data_found;
23 END IF;
24 CLOSE cur_stock_reorder;
25 --
26 IF v_stock.stock_level >= v_stock.reorder_level THEN
27 -- Stock is not low enough to warrant an order
28 RAISE exc_not_warranted;
29 END IF;
30 --
31 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32 -- Required amount is over-ordering
33 RAISE exc_too_much;
34 END IF;
35 --
36 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37 -- Here goes our code to print the order, passing the finance_factor
38 --
39 exception
40 WHEN exc_zero_quantity THEN
41 DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42 WHEN no_data_found THEN
43 CLOSE cur_stock_reorder;
44 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45 WHEN exc_not_warranted THEN
46 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
47 WHEN exc_too_much THEN
48 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 exc_zero_quantity EXCEPTION;
13 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29its nice article, have put up this one the blog
site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
Introduction to regular expressions ... by CD
When your query takes too long ... by Rob van Wijk
How to pipeline a function with a dynamic number of columns? by ascheffer
PL/SQL 101 : Exception Handling by BluShadow -
I need some help with SQL and PreparedStatement
I have add the PreparedStatement and I'm not to sure if I'm doing it correctly.
When I do a test run on Choose 1 ,2 or 3 I now I get this error.
Error - com.mysql.jdbc.Statement
here is my code below
import java.sql.*;
import java.util.*;
import java.sql.PreparedStatement;
public class DBAssign {
* @param args
static Scanner kbd;
static Connection conn = null;
//adding records...
public static void addRecord(String id, String fname, String lname,
String street, String city, String state, String zip,
String hphone, String ophone, String deptasg, int yrsemp,
float mtpy) throws SQLException {
// make variables
PreparedStatement statement = null;
String addstring = "Insert into emptable values('" + id + "', '"
+ fname + "', " + lname + ", '" + street + "'" + city + "',"
+ state + "'," + zip + "'," + hphone + "'," + ophone + "'"
+ deptasg + "'," + yrsemp + "'," + mtpy + "',)";
try {
statement=conn.prepareStatement("INSERT into user values(?,?)");
statement = (PreparedStatement) conn.createStatement();
boolean ret = statement.execute(addstring);
if (ret) {
System.out.println("Updated " + statement.getUpdateCount());
}//close if
} catch (SQLException e) {
System.out.println("Error " + e.getMessage());
throw (e);
} finally {
try {
if (statement != null) {
statement.close();
}//close if
} catch (SQLException e2) {
System.out
.println("Error freeing resources " + e2.getMessage());
throw (e2);
}//close e2
}//close finally
}//close exception
//add to the record
public static void addToTable() {
// get data from keyboard
String id = null;
String fname; // =null;
String lname;
String street;
String city;
String state;
String zip;
String hphone;
String ophone;
String deptasg;
int yrsemp;
float mtpy;
boolean dupkey = true;
while (dupkey == true) {
System.out.println("Enter Employee's ID");
id = kbd.next();
kbd.nextLine();
dupkey = findRecord(id);
if (dupkey == true) {
System.out.println("Key must be unique - try again");
System.out.println("Enter first name");
fname = kbd.next();
kbd.nextLine();
System.out.println("Enter last name");
lname = kbd.next();
kbd.nextLine();
System.out.println("Enter street name");
street = kbd.next();
kbd.nextLine();
System.out.println("Enter city");
city = kbd.next();
kbd.nextLine();
System.out.println("Enter state");
state = kbd.next();
kbd.nextLine();
System.out.println("Enter zip code");
zip = kbd.next();
kbd.nextLine();
System.out.println("Enter home phone number");
hphone = kbd.next();
kbd.nextLine();
System.out.println("Enter office phone");
ophone = kbd.next();
kbd.nextLine();
System.out.println("Enter dept name");
deptasg = kbd.next();
kbd.nextLine();
System.out.println("Enter years employeed");
yrsemp = kbd.nextInt();
kbd.nextLine();
System.out.println("Enter month pay");
mtpy = kbd.nextFloat();
kbd.nextLine();
try {
addRecord(id, fname, lname, street, city, state, zip, hphone,
ophone, deptasg, yrsemp, mtpy);
} catch (SQLException e) {
System.out.println("Error adding record " + e.getMessage());
}//close add
//List records
public static void listRecords() {
PreparedStatement statement = null;
ResultSet rs = null;
try {
statement = (PreparedStatement) conn.createStatement();
rs = statement
.executeQuery("Select empid, firstname, lastname, street, city, state, zip, homephone, officephone, department, yearsemploy, monthpay");
if (rs != null) {
while (rs.next()) {
System.out.println(rs.getString("empid") + " - "
+ rs.getString("firstname") + " - "
+ rs.getInt("lastname") + " - "
+ rs.getString("street") + " - "
+ rs.getString("city") + " - "
+ rs.getString("state") + " - "
+ rs.getString("zip") + " - "
+ rs.getString("hphone") + " - "
+ rs.getString("ophone") + " - "
+ rs.getString("department") + " - "
+ rs.getString("yearsemploy") + " - "
+ rs.getString("monthpay"));
}// close the while loop
}// close the if loop
} catch (SQLException e) {
System.out.println("Error listing records: " + e.getMessage());
} finally {
try {
if (statement != null) {
statement.close();
if (rs != null) {
rs.close();
} catch (SQLException e2) {
System.out.println("Error freeing resource" + e2.getMessage());
}//close finally
}//close list
//Find a record
public static boolean findRecord(String empid) {
boolean retval = true;
PreparedStatement statement = null;
ResultSet rs = null;
int countemps = 0;
try {
statement = (PreparedStatement) conn.createStatement();
rs = statement
.executeQuery("Select count(*) as num from emptable where empid = '"
+ empid + "'");
rs.next();
if (rs == null) {
retval = false;
} else {
countemps = rs.getInt(1);
// System.out.println("Count "+countrecs);
if (countemps <= 0) {
retval = false;
} catch (SQLException e) {
System.out.println("Error finding Employees record "
+ e.getMessage());
} finally {
try {
if (statement != null) {
statement.close();
if (rs != null) {
rs.close();
} catch (SQLException e2) {
System.out.println("Error freeing resource " + e2.getMessage());
retval = true;
}//close finally
return retval;
}//close find
//updates records
public static void updateRecord() {
// get record to update
String id = null;
boolean findemp = false;
while (!findemp) {
System.out.println("Enter Employee ID to update");
id = kbd.next();
kbd.nextLine();
findemp = findRecord(id);
if (!findemp) {
System.out.println("This Employee id record " + id
+ " does not exist - try again");
}//close while
// display data and request update
Statement stmt = null;
ResultSet rs = null;
String id2 = null;
String fname;
String lname;
String street;
String city;
String state;
String zip;
String hphone;
String ophone;
String deptasg;
String yrsemp;
String mtpy;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("Select * from emptable where empid = '"
+ id + "'");
rs.next();
System.out.println("Item First Name is "
+ rs.getString("firstname"));
System.out.print("Enter new item name: ");
fname = kbd.next();
kbd.nextLine();
System.out.println("Item Last name is " + rs.getString("lastname"));
System.out.print("Enter new item name: ");
lname = kbd.next();
kbd.nextLine();
System.out.println("Item Street is " + rs.getString("street"));
System.out.print("Enter new item name: ");
street = kbd.next();
kbd.nextLine();
System.out.println("Item City name is " + rs.getString("city"));
System.out.print("Enter new item name: ");
city = kbd.next();
kbd.nextLine();
System.out.println("Item State name is " + rs.getString("state"));
System.out.print("Enter new item name: ");
state = kbd.next();
kbd.nextLine();
System.out.println("Item Zip Code is " + rs.getString("zip"));
System.out.print("Enter new item name: ");
zip = kbd.next();
kbd.nextLine();
System.out.println("Item Home Phone is " + rs.getString("homephone"));
System.out.print("Enter new item name: ");
hphone = kbd.next();
kbd.nextLine();
System.out.println("Item Office Phone is " + rs.getString("officephone"));
System.out.print("Enter new item name: ");
ophone = kbd.next();
kbd.nextLine();
System.out.println("Item Department is " + rs.getString("department"));
System.out.print("Enter new item name: ");
deptasg = kbd.next();
kbd.nextLine();
System.out.println("Item Years Employed is " + rs.getString("yearsemploy"));
System.out.print("Enter new item name: ");
yrsemp = kbd.next();
kbd.nextLine();
System.out.println("Item Monthly pay is " + rs.getString("monthpay"));
System.out.print("Enter new item name: ");
mtpy = kbd.next();
kbd.nextLine();
String updatestring = "Update emptable set FirstName = '" + fname
+ "', Last name=" + lname + ", street='" + street
+ "', City=" + city + ", State=" + state + ", Zip Code="
+ zip + ", Home Phone=" + hphone + ", Office Phone="
+ ophone + ", Department=" + deptasg + ",Monthly=" + mtpy
+ " Years Employed=" + yrsemp + " where empid = '" + id2
+ "'";
stmt.execute(updatestring);
int updatenum = stmt.getUpdateCount();
if (updatenum < 1) {
System.out.println("Error on update");
} else {
System.out.println("Updated " + updatenum + " records");
} catch (SQLException e) {
System.out.println("Error - " + e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
if (rs != null) {
rs.close();
} catch (SQLException e2) {
System.out.println("Error " + e2.getMessage());
}//close finally
}//close updates
//deleted the record (this section is working
public static void deleteRecord() {
Statement stmt = null;
String delstring;
String id;
try {
stmt = conn.createStatement();
boolean findrec = false;
while (!findrec) {
System.out.println("Enter Employee ID to delete");
id = kbd.next();
kbd.nextLine();
findrec = findRecord(id);
if (!findrec) {
System.out.println("This Employee id record " + id
+ " does not exist - try again");
}//close if
// delete record
delstring = "Delete from emptable where empid = '" + id + "'";
stmt.execute(delstring);
System.out.println("Deleted " + stmt.getUpdateCount()
+ " records");
}//close while
} catch (SQLException e) {
System.out.println("Error deleting record " + e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
} catch (SQLException e2) {
System.out.println("Error removing employee info");
}//close finally
}//close public
public static void showMenu() {
System.out.println("---------------");
System.out.println("1. List employees records");
System.out.println("2. Add employees record");
System.out.println("3. Update employees record");
System.out.println("4. Delete employees record");
System.out.println("5. Exit");
public static int getOption() {
int optn = 99;
while (optn > 5 || optn < 1) {
System.out.println("---");
System.out.println("Enter option");
System.out.print("===>");
optn = kbd.nextInt();
}//close while
return optn;
public static void main(String[] args) {
int optn = 99;
String host = "localhost";
String database = "empdata";
String user = "root";
String pass = "";
// make keyboard object
kbd = new Scanner(System.in);
String connstring = "jdbc:mysql://" + host + "/" + database + "?user="
+ user + "&password=" + pass;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(connstring);
while (optn != 5) {
showMenu();
optn = getOption();
switch (optn) {
case 1:
listRecords();
break;
case 2:
addToTable();
break;
case 3:
updateRecord();
break;
case 4:
deleteRecord();
case 5:
System.out.println("OK - later Come back soon");
default:
break;
}//close switch
}//close while
} catch (ClassNotFoundException e1) {
System.out.println("ERROR - Class not found " + e1.getMessage());
} catch (SQLException e2) {
System.out.println("ERROR - " + e2.getMessage());
System.out.println("ERROR - " + e2.getSQLState());
} catch (Exception e3) {
System.out.println("Error - " + e3.getMessage());
}//close main
}//close classAny help would be great.
Redstatement=conn.prepareStatement("INSERT into user values(?,?)");
statement = (PreparedStatement) conn.createStatement();
boolean ret = statement.execute(addstring);Why are you assigning statement twice?
Example of a prepared statement as follows:
String insertStr = "SELECT fname, lname FROM Person WHERE mName = ?";
PreparedStatement pStmt = conn.prepareStatement (insertStr);
pStmt.setString(index, middleName);
pStmt.execute(); -
Hi
Database 10.1.0.4
Sql trace file which I have used but didn't get the trace file. I have tried to get per session Id but not able to get the trace file, when ever user logged into application, virtually 6 user get lgged in and you never know about user. So I have desided to capture for schema
I have used this for tracing
SQL> ALTER SESSION SET sql_trace=TRUE;
SQL> ALTER SESSION SET sql_trace=FALSE;
Or
SQL> EXEC DBMS_SESSION.set_sql_trace(sql_trace => TRUE);
SQL> EXEC DBMS_SESSION.set_sql_trace(sql_trace => FALSE);
or
SQL> EXEC DBMS_SYSTEM.set_sql_trace_in_session(sid=>123, serial#=>1234, sql_trace=>TRUE);
SQL> EXEC DBMS_SYSTEM.set_sql_trace_in_session(sid=>123, serial#=>1234, sql_trace=>FALSE);
I want to get trace file for schema, can anyone suggest how do I get trace file at schema level.
Thanks for helpHi,
Using instance-level tracing by setting the init.ora/spfile... parameter SQL_TRACE=TRUE, all processes against the instance will create their own trace files. This particular method of tracing should be used with care since it creates a great deal of overhead against the system. In addition, the default value for this parameter is FALSE.
Cheers
Legatti -
After executing sql from batch, its disconnecting
Hello All,
I have written a batch program to execute a pl/sql procedure. But after execution, it disconnects.
But i want to continue in the same session
echo exec tracer.trace_pck.start_('alter session set sql_trace=true') | sqlplus hr/hr
Output:
Press any key to Enable Tracing
SQL*Plus: Release 11.2.0.2.0 Production on Thu Oct 10 15:59:56 2013
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
SQL>
PL/SQL procedure successfully completed.
SQL> Disconnected from Oracle Database 11g Express Edition Release 11.2.0.2.0 -
Production
Trace Enabled Successfully. Press any key to input you sqlIf you are using a batch file I assume you are using the windows OS.
Essentially what you need to do is to call a sql file from the batch file and then get the sql file to call all the other files.
Batchfile test.bat calls sql file test.sql
sqlplus <username>/password @test.sql
test.sql calls test1.sql and test2.sql and then exits
@test1.sql;
@test2.sql;
exit;
test1.sql shows the current sid, and serial# fro our session and our filename
select 'test1',sid,serial# from v$session
where audsid=userenv('sessionid');
test2.sql shows the current sid, and serial# for our session and our filename
select 'test2',sid,serial# from v$session
where audsid=userenv('sessionid');
When you run this you get t output similar to the following: (Your SID and Serial# will be different )
'TEST SID SERIAL#
test1 771 97
'TEST SID SERIAL#
test2 771 97
This shows that two separate sql files were called but are still in the same session -
PreparedStatement with a mssqlserver4v65 DataSource
We have been trying to boost our performance by using PreparedStatement
with the WLS MSSQL Driver, but gained none. Are any of you out there
using PreparedStatements with that driver and noticing performance
improvement?
On a related note, what could we possibly do so wrong with that driver
that would annihilate the performance boost we should have gained? If we
switch to another driver with the exact same code, we see that we gain a
noticable performance gain thanks to the use of PreparedStatements.
Any idea?
Thanks,
ChristopheThanks for your active feedback, Slava. Joe explained everything in
another email in this thread.
And Joe, since you seem to read every post, a BIG THANKS to you too!
Christophe
Slava Imeshev wrote:
Christophe,
First, you have to close result set explicitly.
Second, you say you don't see performance gain.
What did you use to compare performance of prepared
statement?
Regards,
Slava Imeshev
"Christophe Warland" <christophe.warland_REM@OVE_s1.com> wrote in message
news:3C60270F.4060900@OVE_s1.com...
We are using WLS 6.1 SP1.
Our code is actually part of a huge piece of our architecture, so I can
not easily give something to you that would compile on your machine. But
it would look like the following excerpt. 'runTest' acquires a
connection from a JNDI DataSource, creates a PreparedStatement and then
loops on 'testItSingle'.
public long runTest() throws Exception {
long start = System.currentTimeMillis();
// acquire connection from JNDI datasource
// (not shown here)
Connection con = getConnection();
String sql = getSql();
PreparedStatement st = con.prepareStatement(sql);
for (int i = 0; i < TEST_LEN; ++i) {
testItSingle(i, st);
close(st);
close(con);
long end = System.currentTimeMillis();
return end - start;
protected void testItSingle(int i, PreparedStatement st)
throws Exception {
String[] elem = DATA;
String p1 = elem[0]; // acct id
String p3 = elem[1]; // prod code
st.setString(1, p1);
st.setLong(2, ISOCode);
st.setString(3, p3);
ResultSet rs = st.executeQuery();
protected String getSql() {
return "SELECT A.versionStamp AS aLockValue, B.versionStamp AS
bLockValue, A.VFMAcctKy, A.SECEntityKy, A.VFMProductKy, A.acctID,
A.ISOCurrencyCdKy, A.isSrcXferEnabled, A.isDestXferEnabled,
A.maxXferAmt, A.minXferAmt, A.maxPmtAmt, A.minPmtAmt, A.versionStamp,
ledgerBal, ledgerBalDttm, availBal, availBalDttm, overdraftBal,
overdraftBalDttm, ytdInt, ytdIntDttm, lstYrInt, lstYrIntDttm, sumField1,
sumField2, sumField3, sumField4, sumField5, sumField6, sumField7,
sumField8, sumField9, sumField10, sumField11, sumField12, sumField13,
sumField14, sumField15, sumField16, sumField17, sumField18, sumField19,
sumField20 , E.VFMProdSubTypeKy, null VFMCustomerKy FROM VFMAcct A,
VBMDepositAcct B, VFMProduct E WHERE A.VFMAcctKy = B.VFMAcctKy AND
E.VFMProductKy = A.VFMProductKy AND A.acctID = ? AND A.ISOCurrencyCdKy =
? AND E.productCode = ? ORDER BY E.VFMProdSubTypeKy";
We also try to close statement and result set inside 'testItSingle' but
it didn't imporve anything. The preparedstament was actually reopened
silently and running just fine.
Thanks for your help,
Christophe
Slava Imeshev wrote:
Christophe,
Which version of weblogic and service pack do you use?
Could you show us your questionable code? -
How can I program a PL/SQL procedure/function to return a cursor (recordset) to JDBC calling program AND have Oracle NOT reparse the select statement in the package?
I presently return a ref cursor which works, but am dismayed that the statement is hard parsed each and every execution.
thanks..........I think you are using Statement rather than PreparedStatement when you execute your SQL. PreparedStatement uses bind variables and hence avoids multiple hard parses.
Cheers, APC -
I tried putting the square brackets and still get the same error. endasil suggested that the last value being inserted is not looking at the java code. I had earlier put +array. Now I replaced that with +a where a is a string representation of array elements. I still ahve a problem. How can I represent the array element in the query?
String insertCommand = "INSERT into MetricOutput([A1],[A],[DRR],[DeRR],[RE],[WDRR],[WDeRR],[WRE],[ARF],[SRF],[HRF],[WARF],[WSRF],[WHRF],[SDC],[WSDC],[MAR],[WMAR],[H1],[H11],[H2],[H21],[Cluster]) "+
"VALUES("+comMappedCount+","+stdCount+","+DRR+","+DeRR+","+RE+","+WDRR+","+WDeRR+","+WRE+","+ARF+","+SRF+","+HRF+","+WARF+","+WSRF+","+WHRF+","+SDC+","+WSDC+","+MAR+","+WMAR+","+H1+","+H11+","+H2+","+H21+",+a)";It's quite hard to spot without code tags, but aren't you missing some quotes here:
+",+a)"; instead of +","+a+")";I also don't know the Access sql syntax at all, but I am wondering if you don't need to surround all those arguments with single quotes. To avoid these kind of syntax errors in sql: use PreparedStatement. For more on this: http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html -
PreparedStatement with IN clause
Hi,
I have a question regarding using a PreparedStatement and a query
using an IN clause.
I need to pass an array of values to using an IN clause. How does the
binding work in this case since I am getting an SQLException - Invalid
column type ?
I need to pass an array of longs to this query.
The java.sql.Array does not have an implementation. How does this do
this ?Aswin Dinakar wrote:
>
Thanks a lot ! You really understood my problem without me describing it
properly.
I dont mind keeping it as a statement but that statement is being executed in
a FOR loop thousands of times and its a very complex SQL with lots of joins
and its taking up a lot of the CPU. Time constraint prevent me from changing
the business logic.I also suggest making a stored procedure to do the complex stuff. At least the
DBMS will only have to parse it once. The argument could even be a string
like "1,2,3,4,5,6", and the procedure could handle separating the values.
In a related issue do you know if the JMS database updates(deletes mostly) for
WLS 5.1 are PreparedStatement(s) ? When I query the v$sqlarea table for the
parse counts I see lots of JMS updates to the database.yes they are, but our MS SQLServer driver is inefficient about SQL with
PreparedStatements, sending fresh SQL to be parsed each execution. I suggest
your trying the MS driver from www.inetsoftware.de, which will do a better jod
than ours in this area.
Joe
>
Joseph Weinstein wrote:
A PreparedStatement only allows settable parameters representing
single values. You can't do:
stmt = c.prepareStatement("select * from foo where key in ?");
stmt.setString(1, "(1,2,3,4,5,6)");
Therefore, you need to know how many values in your In clause,
and generate a PreparedStatement like:
stmt = c.prepareStatement("select * from foo where key in (?,?,?,?,?...");
with a '?' for every value. Depending on whose driver your using, and
whether you can keep and re-use PreparedStatments, it might be better
to simply make the whole SQL query as a simple string and execute it:
String query = "select * from foo where key in (1,2,3,4,5,6)";
rs = stmt.executeQuery(query);
Aswin Dinakar wrote:
Hi,
I have a question regarding using a PreparedStatement and a query
using an IN clause.
I need to pass an array of values to using an IN clause. How does the
binding work in this case since I am getting an SQLException - Invalid
column type ?
I need to pass an array of longs to this query.
The java.sql.Array does not have an implementation. How does this do
this ? -
Unable to run Web App for the 2nd Time
Hi,
I am using Weblogic 8.1 sp5 as my deploying platform. Using the official tutorials, I am able to export my JSC2 web app into a WAR file that is deployable on my Weblogic server.
Upon running the application, it works perfectly. However, upon closing my browser and then restarting the browser, running the web app again yields exceptions, please refer to the bottom.
What am I doing wrong? I am suspecting the web-app wasn't detroyed properly when another instances of it is started...
Please advise.
Adams
Error 500--Internal Server Error
com.sun.rave.web.ui.appbase.ApplicationException: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Invalid parameter binding(s).
at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.destroy(Ljavax/faces/context/FacesContext;)V(ViewHandlerImpl.java:601)
at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIViewRoot;)V(ViewHandlerImpl.java:316)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(Ljavax/faces/context/FacesContext;)V(RenderResponsePhase.java:87)
at com.sun.faces.lifecycle.LifecycleImpl.phase(Ljavax/faces/event/PhaseId;Lcom/sun/faces/lifecycle/Phase;Ljavax/faces/context/FacesContext;)V(LifecycleImpl.java:221)
at com.sun.faces.lifecycle.LifecycleImpl.render(Ljavax/faces/context/FacesContext;)V(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(FacesServlet.java:198)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava/lang/Object;(ServletStubImpl.java:1072)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Lweblogic/servlet/internal/FilterChainImpl;)V(ServletStubImpl.java:465)
at weblogic.servlet.internal.TailFilter.doFilter(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Ljavax/servlet/FilterChain;)V(TailFilter.java:28)
at weblogic.servlet.internal.FilterChainImpl.doFilter(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(FilterChainImpl.java:27)
at com.sun.rave.web.ui.util.UploadFilter.doFilter(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Ljavax/servlet/FilterChain;)V(UploadFilter.java:194)
at weblogic.servlet.internal.FilterChainImpl.doFilter(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(FilterChainImpl.java:27)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(RequestDispatcherImpl.java:326)
at weblogic.servlet.jsp.PageContextImpl.forward(Ljava/lang/String;)V(PageContextImpl.java:150)
at jsp_servlet.__jscreator_index._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V(__jscreator_index.java:122)
at weblogic.servlet.jsp.JspBase.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(JspBase.java:33)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava/lang/Object;(ServletStubImpl.java:1072)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Lweblogic/servlet/internal/FilterChainImpl;)V(ServletStubImpl.java:465)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(ServletStubImpl.java:348)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run()Ljava/lang/Object;(WebAppServletContext.java:6985)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(Lweblogic/security/subject/AbstractSubject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Lweblogic/security/acl/internal/AuthenticatedSubject;Lweblogic/security/acl/internal/AuthenticatedSubject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(Lweblogic/servlet/internal/ServletRequestImpl;Lweblogic/servlet/internal/ServletResponseImpl;)V(WebAppServletContext.java:3892)
at weblogic.servlet.internal.ServletRequestImpl.execute(Lweblogic/kernel/ExecuteThread;)V(ServletRequestImpl.java:2766)
at weblogic.kernel.ExecuteThread.execute(Lweblogic/kernel/ExecuteRequest;)V(ExecuteThread.java:224)
at weblogic.kernel.ExecuteThread.run()V(ExecuteThread.java:183)
at java.lang.Thread.startThreadFromVM(Ljava/lang/Thread;)V(Unknown Source)
Caused by: java.lang.RuntimeException: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Invalid parameter binding(s).
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorRow(Lcom/sun/data/provider/RowKey;)V(CachedRowSetDataProvider.java:343)
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorIndex(I)Z(CachedRowSetDataProvider.java:300)
at com.sun.data.provider.impl.CachedRowSetDataProvider.getRowCount()I(CachedRowSetDataProvider.java:624)
at com.sun.rave.web.ui.component.TableRowGroup.getRowKeys()[Lcom/sun/data/provider/RowKey;(TableRowGroup.java:806)
at com.sun.rave.web.ui.component.TableRowGroup.getFilteredRowKeys()[Lcom/sun/data/provider/RowKey;(TableRowGroup.java:429)
at com.sun.rave.web.ui.component.TableRowGroup.getRowCount()I(TableRowGroup.java:749)
at com.sun.rave.web.ui.component.Table.getRowCount()I(Table.java:307)
at com.sun.rave.web.ui.component.Table.getTableActionsTop()Ljavax/faces/component/UIComponent;(Table.java:539)
at com.sun.rave.web.ui.renderer.TableRenderer.renderActionsTop(Ljavax/faces/context/FacesContext;Lcom/sun/rave/web/ui/component/Table;Ljavax/faces/context/ResponseWriter;)V(TableRenderer.java:257)
at com.sun.rave.web.ui.renderer.TableRenderer.encodeBegin(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIComponent;)V(TableRenderer.java:124)
at javax.faces.component.UIComponentBase.encodeBegin(Ljavax/faces/context/FacesContext;)V(UIComponentBase.java:683)
at com.sun.rave.web.ui.component.Table.encodeBegin(Ljavax/faces/context/FacesContext;)V(Table.java:811)
at com.sun.rave.web.ui.util.RenderingUtilities.renderComponent(Ljavax/faces/component/UIComponent;Ljavax/faces/context/FacesContext;)V(RenderingUtilities.java:78)
at com.sun.rave.web.ui.renderer.AbstractRenderer.encodeChildren(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIComponent;)V(AbstractRenderer.java:194)
at javax.faces.component.UIComponentBase.encodeChildren(Ljavax/faces/context/FacesContext;)V(UIComponentBase.java:701)
at javax.faces.webapp.UIComponentTag.encodeChildren()V(UIComponentTag.java:607)
at javax.faces.webapp.UIComponentTag.doEndTag()I(UIComponentTag.java:544)
at jsp_servlet.__vesselsmovements._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V(__vesselsmovements.java:1060)
at weblogic.servlet.jsp.JspBase.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(JspBase.java:33)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava/lang/Object;(ServletStubImpl.java:1072)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Lweblogic/servlet/internal/FilterChainImpl;)V(ServletStubImpl.java:465)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(ServletStubImpl.java:348)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(RequestDispatcherImpl.java:328)
at com.sun.faces.context.ExternalContextImpl.dispatch(Ljava/lang/String;)V(ExternalContextImpl.java:322)
at com.sun.faces.application.ViewHandlerImpl.renderView(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIViewRoot;)V(ViewHandlerImpl.java:130)
at com.sun.rave.web.ui.appbase.faces.ViewHandlerImpl.renderView(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIViewRoot;)V(ViewHandlerImpl.java:311)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(Ljavax/faces/context/FacesContext;)V(RenderResponsePhase.java:87)
at com.sun.faces.lifecycle.LifecycleImpl.phase(Ljavax/faces/event/PhaseId;Lcom/sun/faces/lifecycle/Phase;Ljavax/faces/context/FacesContext;)V(LifecycleImpl.java:221)
at com.sun.faces.lifecycle.LifecycleImpl.render(Ljavax/faces/context/FacesContext;)V(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(FacesServlet.java:198)
at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run()Ljava/lang/Object;(ServletStubImpl.java:1072)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;Lweblogic/servlet/internal/FilterChainImpl;)V(ServletStubImpl.java:465)
Caused by: java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Invalid parameter binding(s).
at com.microsoft.jdbc.base.BaseExceptions.createException(Ljava/lang/String;Ljava/lang/String;)Ljava/sql/SQLException;(Unknown Source)
at com.microsoft.jdbc.base.BaseExceptions.getException(ILjava/lang/String;)Ljava/sql/SQLException;(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.validateParameters(Lcom/microsoft/jdbc/base/BaseParameters;)V(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.validateParameters()V(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.preImplExecute()V(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.commonExecute()V(Unknown Source)
at com.microsoft.jdbc.base.BaseStatement.executeQueryInternal()Ljava/sql/ResultSet;(Unknown Source)
at com.microsoft.jdbc.base.BasePreparedStatement.executeQuery()Ljava/sql/ResultSet;(Unknown Source)
at weblogic.jdbc.wrapper.PreparedStatement.executeQuery()Ljava/sql/ResultSet;(PreparedStatement.java:124)
at com.sun.sql.rowset.internal.CachedRowSetXReader.readData(Ljavax/sql/RowSetInternal;)V(CachedRowSetXReader.java:193)
at com.sun.sql.rowset.CachedRowSetXImpl.execute(Ljava/sql/Connection;)V(CachedRowSetXImpl.java:950)
at com.sun.sql.rowset.CachedRowSetXImpl.execute()V(CachedRowSetXImpl.java:1410)
at com.sun.data.provider.impl.CachedRowSetDataProvider.checkExecute()V(CachedRowSetDataProvider.java:1219)
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorRow(Lcom/sun/data/provider/RowKey;)V(CachedRowSetDataProvider.java:329)
at com.sun.data.provider.impl.CachedRowSetDataProvider.setCursorIndex(I)Z(CachedRowSetDataProvider.java:300)
at com.sun.data.provider.impl.CachedRowSetDataProvider.getRowCount()I(CachedRowSetDataProvider.java:624)
at com.sun.rave.web.ui.component.TableRowGroup.getRowKeys()[Lcom/sun/data/provider/RowKey;(TableRowGroup.java:806)
at com.sun.rave.web.ui.component.TableRowGroup.getFilteredRowKeys()[Lcom/sun/data/provider/RowKey;(TableRowGroup.java:429)
at com.sun.rave.web.ui.component.TableRowGroup.getRowCount()I(TableRowGroup.java:749)
at com.sun.rave.web.ui.component.Table.getRowCount()I(Table.java:307)
at com.sun.rave.web.ui.component.Table.getTableActionsTop()Ljavax/faces/component/UIComponent;(Table.java:539)
at com.sun.rave.web.ui.renderer.TableRenderer.renderActionsTop(Ljavax/faces/context/FacesContext;Lcom/sun/rave/web/ui/component/Table;Ljavax/faces/context/ResponseWriter;)V(TableRenderer.java:257)
at com.sun.rave.web.ui.renderer.TableRenderer.encodeBegin(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIComponent;)V(TableRenderer.java:124)
at javax.faces.component.UIComponentBase.encodeBegin(Ljavax/faces/context/FacesContext;)V(UIComponentBase.java:683)
at com.sun.rave.web.ui.component.Table.encodeBegin(Ljavax/faces/context/FacesContext;)V(Table.java:811)
at com.sun.rave.web.ui.util.RenderingUtilities.renderComponent(Ljavax/faces/component/UIComponent;Ljavax/faces/context/FacesContext;)V(RenderingUtilities.java:78)
at com.sun.rave.web.ui.renderer.AbstractRenderer.encodeChildren(Ljavax/faces/context/FacesContext;Ljavax/faces/component/UIComponent;)V(AbstractRenderer.java:194)
at javax.faces.component.UIComponentBase.encodeChildren(Ljavax/faces/context/FacesContext;)V(UIComponentBase.java:701)
at javax.faces.webapp.UIComponentTag.encodeChildren()V(UIComponentTag.java:607)
at javax.faces.webapp.UIComponentTag.doEndTag()I(UIComponentTag.java:544)
at jsp_servlet.__vesselsmovements._jspService(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V(__vesselsmovements.java:1060)
at weblogic.servlet.jsp.JspBase.service(Ljavax/servlet/ServletRequest;Ljavax/servlet/ServletResponse;)V(JspBase.java:33)Well, I have solve this problem myself.. apparently, I used static variables to initalise the app. Changing the static variables to session variables solved the problems.
Maybe you are looking for
-
I have a substitution variable in report script for current week. Trying to add two more columns with the two prior weeks. Is there a command for that?
-
Setting Markers in Log & Transfer window
Hi All Anyone know a trick/plug-in that will enable me to set markers while I am setting my In's and Out's in the Log & Transfer Window before I 'Add Clip to Queue'? I would like to set markers indicating the interesting moments in the footage. cheer
-
I am using a Canon MP530 to print my photos from IPhoto. All my blacks have purple in them. The Canon staff worked with me and it is not the printer, as when I print from Photo Elements, it doesn't happen. Does anyone have any suggestions?
-
Safari 6.0.5 crashing on certain sites
Safari is continually crashing on certain sites. Such as ESPN and a site with a java based game called warlight.net. I have done everything I can think of. Im a new MBP owner. So im in a bit of uncharted territory here. I could use some major help he
-
Revision: 10085 Author: [email protected] Date: 2009-09-09 07:39:54 -0700 (Wed, 09 Sep 2009) Log Message: Fixing video width and height getting reset when there's no true dimensional change reported by 'onMetaData'. Modified Paths: osmf/tru