Why do we need Prepared Statement?

Why do we need Prepared Statement ? How it is better tha Statement ?
Why cant we use Callable Statement instead of Prepared Statement?

Statement is a generic SQL statement you build yourself. PreparedStatement is also a SQL statement; however, the bind variables do not have to be escaped (e.g., you do not need to surround a string with quotes). Another benefit of PreparedStatements is that the JDBC driver can cache them for subsequent re-use, eliminating the parsing step and improving response time. Finally, CallableStatement is to execute a stored procedure, not a SQL statement.
In general, use PreparedStatement over Statement if possible. Use CallableStatement only for stored procedures.
- Saish

Similar Messages

  • Why do we need retained earnings account in income statement?

    hi,
    as far as i am concerned we need a retained earnings account only in a balance sheet statement. however i dont understand why do we need a retained earnings account in the income statement. can someone explain?

    Hi
    The account nothing but contains the accumulated profits which are divisible to the shareholders carry forward from the P&L account.
    we define Retained earnings a/c in OB53.
    Most companies use one retained earnings account. For this reason, X can be used as the key.
    In the chart of accounts you enter X in the P+L statement account type field, and for account determination you enter the retained earnings account under the key X
    assign points if useful

  • Why do we need to code  loop statement in both PBO and PAI in Table control

    Hi friends,
    i have 2 questions-
    Q1-why do we need to code a loop and endloop statement in both PBO and PAI in Table control,sometimes even empty as well?
    Q2-what r d dynpro keywords?

    Hi,
    It is required to pass information from internal table to table control so we loop it in PBO and to get the updated information back, we loop in PAI and update internal table content.
    To get more knowledge on Table controls check these threads -
    table control
    Table Control
    Hope this helps.
    ashish

  • ArrayIndexOutOfBoundsException when setting a date in a prepared statement

    Hi,
    was wondering if anyone could help. I have a prepared statement, with two "variables" in it. I need to set the first of these to a string (using setString(1, "string)
    and the second to a date, using setDate(2, SQLDate)
    My SQL date is a valid date ass I've run a debugger and checked, but everytime setDate is called an Array Out Of Bound Exception is thrown. Can anyone shed any light on this as I'm rather confused as to why this is happening!
    Thanks in advance

    I havent got a small runnable example to hand, but taking an excert from my code I have:
    for (int i = 0; i < this.columnNames.size();i++)
    singleDateEventFlagSingleArea.setString(1, newAreaName);
    singleDateEventFlagSingleArea.setDate(2, Date.valueOf((String) this.columnNames.get(i)));
    eventFlagsResult = singleDateEventFlagSingleArea.executeQuery()
    }newAreaName is a argument passed to the method. columnNames is a vector of dates/strings, which I parse back into a date to pass to the setDate method
    Where the value of the date in the statement is changed to a preset value each iteration.
    The exception stack I'm getting is:
    exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
         at oracle.jdbc.dbaccess.DBDataSetImpl._getDBItem(DBDataSetImpl.java:378)
         at oracle.jdbc.dbaccess.DBDataSetImpl._createOrGetDBItem(DBDataSetImpl.java:781)
         at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2399)
         at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1134)
         at oracle.jdbc.driver.OraclePreparedStatement.setDate(OraclePreparedStatement.java:2223)
         at treeTableVersion2.TreeTable.updateValuesSingleDateSingleArea(TreeTable.java:393)
         at treeTableVersion2.TestWindow.actionPerformed(TestWindow.java:394)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1774)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Although I think a lot of that is because the process is called by a button press.
    The sql statement thats causing the problem is:
    select h.areaname,
           e.code,
           e.descript,
           ec.date_raised,
           ec.date_progressing,
           ec.date_completed
      from hareas h, evt_type e, evt_core ec
    where h.areaname = ?
       and e.evt_type_id = ec.evt_type_id
       and (h.nblink = ec.area1_nblink or h.nblink = ec.area2_nblink)
       and ec.date_raised = ?
    group by h.areaname,
              e.code,
              e.descript,
              ec.date_raised,
              ec.date_progressing,
              ec.date_completed
    order by h.areanameThanks for your help

  • Oracle Prepared Statement - 8.1.7 JDBC type II Driver

    Hi,
    I have a strange problem.
    I do a query using a prepared statement and there are no matching results.
    I change this to hardcoded SQL Statement and pass in the same value a row of record is returned
    I change this to Statement and pass in the input a row of record is returned.
    This is puzzling. There seems to be a problem with Prepared Statement and I can't see why that fails.
    The Stmt looks like this
    PreparedStatement id is defiend as a char in the database
    Code Snippet:
    SQL = Select * from employee where id = ?;
    pstmt.setString(1,'value');
    Hardcoded SQL:
    select * from employee where id = 'value';
    Statement Impl:
    String var = "value";
    "select * from employee where id = '" + var+ "'";
    Would appreciate if somebody can explain what's happening. To me it is bizarre!
    Thanks,
    Manglu

    Update to problem
    I have the latest (classes12.zip) JDBC drivers from Oracle.
    We are running Oracle 8.1.6 and converting to Oracle 8.1.7.
    This works the same with both.
    Example, I have a column (char(10)) with trailing spaces. i.e. '39 '.
    When I perform a Prepared Statement with that column in the where clause, it returns no result rows.
    When I perform a standard statement with that column in the where clause, it returns rows.
    When I define a column char(2) and use it in the where clause it works fine.
    When I define a column varchar2(10) and load it with data like '39', it works fine.
    When I define a column varchar2(10 and load it with data like '39 ', it does not work.
    When I execute this same Prepared Statement through the jdbc:odbc bridge it works fine.
    I cannot change the definition of the columns as they are foreign key data. What is the problem here? Any help is appreciated.
    If you need further information please feel free to contact me.

  • Why do we need a disabled AD object prior to migrating user from one domain to another.

    Say i am migrating a user 'Mr.A' mailbox from abc.com to xyz.com in exchange 2010 environemnt, why do i need a disabled AD object for Mr. A in xyz.com prior to migrating  ? please suggest.
    Aditya Mediratta

    Hi ,
    To be frank i am not aware of quest but i can suggest you in ADMT and also in exchange cross forest migration.
    I hope you are doing the cross forest migration from exchange forest to exchange forest , so on such case by using the prepare-moverequest.ps1  we can have
    only have the disabled MEU on the target exchange forest until the remaining attributes of the user object was migrated from ADMT.
    While running the prepare-moverequest.ps1  it will not completely move all the active directory user attributes from the source forest to the target forest
    but it will move all the exchange attributes to the target forest and finally it will make the MEU object in the disabled state. Since
    all the exchange attributes are already migrated to the target forest ,so prior to use ADMT user account migration we need to exclude the exchange attributes
    by running the script on the ADMT server .After doing so exchange attributes will not be migrated but the required user attributes will be migrated to make the MEU to the enabled state.
    Reference Link for types of exchange migration between the forest :
    http://blogs.technet.com/b/exchange/archive/2010/08/10/3410619.aspx
    Thanks & Regards S.Nithyanandham

  • Why do we need Segment Reporting?

    Dear Experts,
    Why do we need Segment reporting since Profit Center reporting can do the same?
    Basically what's the difference?
    Regards,
    Abraham

    Hi Abraham,
    This is what IAS -14 AND IFRS -8 says:
    IAS
    Business segment: a component of an entity that (a) provides a single product or service or a group of related products and services and (b) that is subject to risks and returns that are different from those of other business segments. [IAS 14.9]
    IFRS
    that engages in business activities from which it may earn revenues and incur expenses (including revenues and expenses relating to transactions with other components of the same entity)
    So every company which wants to prepare their Financial statements with either IAS or IFRS need to prepare segment wise Balance sheets and P&L accounts also.
    A reportable segment is a business segment which is generating 10% of total revenues and 10% of total profit or loss and which is having 10% of total assets.
    Please get back to me if you need further assistance.
    Regards,
    Ravi.

  • Database prepared statements Flooding

    Hi Friends,
    Need your help to fix this prolonging problem in one of our applications. We observe that the following queries are declared as prepared statements but have dynamic value ROWID in each.
    SELECT ROWID, C. * FROM Table1 C WHERE C.VENDORLOGINID = ? AND C.VENDORTYPE = ? AND (ROWID = _ ROWID100)
    SELECT ROWID, C. * FROM Table2 C WHERE C.VENDORIDCH = ? AND (ROWID = _ ROWID114)
    SELECT ROWID, C. * FROM Table1 C WHERE C.VENDORLOGINIDBASE = ? AND C.VENDORTYPE = ? AND (ROWID = _ ROWID58)
    This results in a FLOOD of prepared statements (over 3000) as it is an application with a very large DB.
    We found out that a newer version of Ojdbc14.jar (10.2.0.3.0) is available (At present we are shipping the product with 10.2.0.1.0). We tested with this newer jar and found out bind variables are not treated as dynamic variables with this jar file. SQL queries are getting cached as expected.
    This new jar file did fix the problem when our DB was 10g for the application (another), but for this current application we are using Oracle 9i.
    The same jar file does not seem to be fixing the issue.
    Has anybody faced similar issue before?
    Ideally the 10g jar file should eb backward compatible but for some reason it is not for this particular problem.
    Please can somebody help to get a solution for this problem. Do let me know if you need more information.
    Thanks.

    This thread is old and undiscussed since first post.
    Don't understand why but i got some ideas.
    1. First of all, i doubt that this is JDBC issue. JDBC PreparedStatement caching has nothing to do with sharability of SQL statements in Oracle.
    If this is JDBC issue, what a silly bug it is... But silly things happen quite often :(
    2. I think some cursor-related views like V$SQL_SHARED_CURSOR, V$SQL and V$SQLAREA should be investigated. The notorious bind mismatch can cause unwanted unshareable SQL statements which look exactly same each other.

  • Dynamically obtain parameter count for a prepared statement

    Hi JDBC Gurus,
    Given a prepared statement, is there a way to figure out the parameter count at runtime? I need this info. to prompt the user for parameter values at the right time from my GUI tool. Any help will be greatly appreciated.

    i don't know of any way to do this put perusing through the API i am wondering what the getMetaData method of PreparedStatement is supposed to do. it says returns the meta data of a ResultSet's columns but i think it could contain info about the parameters for the PreparedStatement. i guess i just don't see why that method is there... anyone?

  • Proving prepared statements are being reused

    How can I prove that a prepared statement from a JDBC driver is being reused / pooled ?
    What essentially I want to do is to have prepared statements reused to reduce hard parsing ... but I also need to prove that the statements are being reused. If I query the statement in V$SQLAREA, the column PARSE_CALLS does not seem to be distinguish between hard parse and soft parse:
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96536/ch3204.htm#1126299
    I am only interested for now in proving the just ONE statement is being reused ... which mean that the number of hard parses is very low compared to the number of soft parses for that ONE statement.
    Regards,
    jms
    Message was edited by:
    jms

    Hi,
    No, parse calls is all soft and hard parse together. What you would see, if used absolutely correctly, would be 1 hard parse per session and many executions.
    But since v$sql is obviously not linked to v$session other than at the time of exection, you see the aggregated parse calls and executions for each cursor. So what you should see is parse calls go up relatively slowly to the number of exections.
    However, you can see soft and hard parses using the v$sesstat and v$statname views so you can see soft and hard parses on a session by session basis, be these are again aggregated, so you can't see soft / hard counts per cursor, only the total for a session.
    What I see a lot of the time is they don't get it quite right, so hard parses is low but soft parses are high, so they are still parsing when they don't need to, but at least they are binding and using shareable SQL, which is a step in the right direction.
    When I say 'they', it is a generic reference to all Java/.Nyet programmers writing front end code where they just don't 'get' parsing and binding because it's just too complicated and hey, SQL Server isn't like this...!
    HTH
    Chris

  • When to use prepared statement in java?

    Hi all,
    If we have query like select * from {tablename} (Here tablename is the variable) then will the use of prepared staement improve the performance? My guess is use of statement in this case is a better option rather than prepared statement as the tablename may change for every other query.I think are not useful if tablename changes.They are useful only when the where clause has dynamic values.

    cantor wrote:
    Are you sure that your approach is possible? The next example causes exception for me.
    PreparedStatement ps = conn.prepareStatement("select * from ?");
    ps.setString(1, "TABLE_NAME");
    ps.executeQuery();
    I didn't say that he should solve it in that way. He should create one prepared statement like this "select a, b, c from tablename1" and another prepared statement when he wants to execute "select d, e, f from tablename2"
    >
    And as I understand, this code will not improve perfomance (and even will not work). As I said it can.
    Prepared statements make possible usage compiled queries inside DB. When DB gets prepared statement call, it need to parse it only once. And it can collect some statistic to improve execution plan. But when table name is not specified, this approach will not work.Yes it might. There are database drivers that can cache prepared statements and it's isn't likely that he executes that query on more than e.g. 20 tables?
    The database can also cache compiled statements in a cache.
    Kaj

  • How do I handle NULL returns from prepared statement?

    Thanks in advance to all those who respond. As a beginner with Java/JSP/JDBC, I need all the help I can get!
    Here's the problem...
    I'm using a prepared statement in JSP to query a MySQL database.
    If there is a value to return, everything works properly.
    If the query returns a NULL (empty set) value, I get the following error:
    javax.servlet.ServletException: Before start of result set
    Here's the code (no negative comments please...I know I'm violating some conventions! I'll restructure it later. Right now I just need help with handling the NULL case):
    <%
    Driver DriverAppt = (Driver)Class.forName(MM_test_DRIVER).newInstance();
    Connection ConnAppt = DriverManager.getConnection(MM_test_STRING,MM_test_USERNAME,MM_test_PASSWORD);PreparedStatement StatementAppt = ConnAppt.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id = " + Recordset1__MMColParam + " AND year = " + yy + " AND month = '" + months[mm] + "' AND date = " + dates[dd] + " AND appttime = '16:15:00'");
    ResultSet Appt = StatementAppt.executeQuery();
    boolean Appt_isEmpty = !Appt.first();
    boolean Appt_hasData = !Appt_isEmpty;
    Object Appt_data;
    int Appt_numRows = 0;
    %>
    Thanks for the help!!!

    I think I have a better handle on what's occurring here. To cut to the heart of the problem, I'm going to give a very simple example that illustrates what type of error handling I need.
    HERE'S THE EXAMPLE:
    Let's say that I have a database of users. There are only two columns in the database: user_id and lastname. There are only 2 users, user_id "1" has lastname "Jones" and user_id "2" has lastname "Smith".
    I built a very simple web interface that let's a user enter a number to see if there's a lastname associated with that record. The user has no way of knowing if the user_id exists or not, so they may or may not enter a valid number.
    If the user enters a valid user_id (in this case "1" or "2"), then the correct lastname is displayed. If the user enters an invalid user_id (in this case, anything other than "1" or "2") then I get the same "Before start of result set" error that I'm getting in my real application.
    So, the question is: WHERE IN THIS CODE WOULD I HANDLE THE RETURN OF AN EMPTY SET?
    The goal here is to have the sentence say "The user's lastname is .", basically returning null. If there has to be a value, then have the last sentence say "The user's lastname is unknown."
    If you can solve this simple example, you'll have also solved the problem with my main application!!!! :-)
    Here's the example code:
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <%@ include file="Connections/example.jsp" %>
    <%
    String Recordset1__MMColParam = "1";
    if (request.getParameter("user_id") !=null) {Recordset1__MMColParam = (String)request.getParameter("user_id");}
    %>
    <%
    Driver DriverRecordset1 = (Driver)Class.forName(MM_example_DRIVER).newInstance();
    Connection ConnRecordset1 = DriverManager.getConnection(MM_example_STRING,MM_example_USERNAME,MM_example_PASSWORD);
    PreparedStatement StatementRecordset1 = ConnRecordset1.prepareStatement("SELECT * FROM test_table WHERE user_id = " + Recordset1__MMColParam + "");
    ResultSet Recordset1 = StatementRecordset1.executeQuery();
    boolean Recordset1_isEmpty = !Recordset1.next();
    boolean Recordset1_hasData = !Recordset1_isEmpty;
    Object Recordset1_data;
    int Recordset1_numRows = 0;
    %>
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <form action="test.jsp" method="get" enctype="application/x-www-form-urlencoded" name="form1" target="_self">
    <p> Submit a user id and a lastname will be displayed.</p>
    <p>
    <input type="text" name="user_id">
    <input type="submit" name="" value="Submit">
    </p>
    </form>
    <p>The User's lastname is <%=(((Recordset1_data = Recordset1.getObject("lastname"))==null || Recordset1.wasNull())?"":Recordset1_data)%>.</p>
    </body>
    </html>
    <%
    Recordset1.close();
    StatementRecordset1.close();
    ConnRecordset1.close();
    %>
    A huge "THANK YOU!!!!" to all those who've helped me here!!!

  • Why do I need to catch this exception?

    Hello all
    This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*; 
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;     
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;                                                                                                                                                                                                                         
    import static java.lang.Math.*;
    public class CalendarAssignment extends JFrame implements ActionListener
         int MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
         public JButton [] days = new JButton[43];
         private JLabel lbl, reminderlbl;
         private JPanel top, grid, remindercenter, reminderbottom;
         private JFrame reminderframe;
         private JTextField year1, reminderinput, dayno;
         private JComboBox months;
         private Container container;
         private JButton fetch, save, cancel;
         private Document doc;
         private File file;
         private Node node;
         private String year, month, day;
              public static void main( String[] args ) {
                   CalendarAssignment c = new CalendarAssignment( );
                   c.setSize( 400, 300 );
                   c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                   c.show( );
              public CalendarAssignment( ) {
                   int CurrentYear, CurrentMonth;
                   String YearString, MonthString, Now;
                   Date today;
                   container = getContentPane( );
                   container.setLayout( new BorderLayout( ) );
                   SimpleDateFormat DateFormatter;
                   DateFormatter = new SimpleDateFormat( "MM.yyyy" );
                   today = new Date( );
                   Now = DateFormatter.format( today );
                   MonthString = Now.substring( 0,2 );
                   YearString = Now.substring( 3,7 );
                   CurrentMonth = Integer.valueOf( MonthString );
                   CurrentYear = Integer.valueOf( YearString );
                   top = new JPanel( );
                        String [] items = { "January", "February", "March", "April", "May", "June",
                                      "July", "August", "September", "October", "November",
                                      "December" };
                        months = new JComboBox( items );
                        months.setEditable( false );
                        months.setSelectedIndex( CurrentMonth - 1 );          
                        year1 = new JTextField( );
                        year1.setText( YearString );
                        year1.setEditable( true );
                        year1.setHorizontalAlignment( year1.CENTER );
                        fetch = new JButton( "Fetch Month" );
                        fetch.addActionListener( this );
                        top.setLayout( new GridLayout( 1, 3, 20, 0 ) );
                        top.add( months );
                        top.add( year1 );
                        top.add( fetch );
                   grid = new JPanel( );
                        grid.setLayout( new GridLayout( 7, 7, 0, 0 ) );
                        String [] week = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
                        for ( int a = 0; a < 7; a ++ ) {
                                  JLabel lbl = new JLabel( week[a], JLabel.CENTER );
                                  grid.add( lbl );
                        for ( int i = 0; i < 42; i ++ ) {
                                  days[i] = new JButton( );
                                  grid.add( days[i] );
                                  days.addActionListener( this );
                        DrawCalendar( CurrentMonth, CurrentYear );
                        container.add( top, BorderLayout.NORTH );
                        container.add( grid, BorderLayout.CENTER );
              private void DrawCalendar( int SelectMonth, int SelectYear ) {
                        int DisplayMonthLength, Buttons;
                        String ButtonID = "";
                        int OffSet = MonthStart( SelectMonth, SelectYear );
                        DisplayMonthLength = MonthLength [SelectMonth - 1];
                        if ( SelectMonth == 2 )
                             DisplayMonthLength += LeapYear( SelectYear );
                        for ( Buttons = 1; Buttons < 43; Buttons ++ ) {
                             if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ) {
                                  ButtonID = "";
                                  days[Buttons-1].setEnabled( false );
                             else {
                                  ButtonID = Integer.toString( Buttons - OffSet );
                                  days[Buttons-1].setEnabled( true );
                        days[Buttons-1].setLabel( ButtonID );
                        grid.add( days[Buttons-1] );
              private int LeapYear( int year ) {
                        int FourHundred, OneHundred, Fourth;
                        FourHundred = year % 400;
                        OneHundred = year % 100;
                        Fourth = year % 4;
                        if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
                             return ( 1 );
                        else
                             return ( 0 );
              private int MonthStart( int Month, int Year ) {
                        int OffSet, LastMonths, BeforeOrAfter, Years;
                        int AllDays = 0;
                        int YearDays = 365;
                        int YearMonths = 12;
                        BeforeOrAfter = Year - 2006;
                        Years = abs( BeforeOrAfter );
                        if( BeforeOrAfter != 0 )
                             BeforeOrAfter = BeforeOrAfter / Years;
                        switch( BeforeOrAfter ) {
                             case 1:
                                  for( int a = 2006; a < Year; a ++ ) {
                                       AllDays += YearDays + LeapYear( a );
                                  AllDays += LastMonthsCalc( Month, Year );
                             break;
                             case -1:
                                  for( int a = 2005; a > Year; a -- ) {
                                       AllDays += YearDays + LeapYear( a );
                                  for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ) {
                                       AllDays += MonthLength[LastMonths - 1];
                                       if( LastMonths == 2 )
                                            AllDays += LeapYear( Year );
                             break;
                             default:
                                  if( Month > 1 )
                                       AllDays += ( LastMonthsCalc( Month, Year ) );
                        OffSet = AllDays % 7;
                        if( BeforeOrAfter ==( -1 ) )
                             return( 6 - OffSet );
                        else if( OffSet > 0 )
                             return( OffSet - 1 );
                        else
                             return( 6 );
              private int LastMonthsCalc( int Month, int Year ) {
                        int Counter;
                        int days = 0;
                        for( Counter = 1; Counter < Month; Counter ++ ) {
                             days += MonthLength[Counter - 1];
                             if( Counter == 2 )
                                  days += LeapYear( Year );
                        return( days );
              public void CreateReminder( String buttonID, String yearID, String monthID ) {
                        reminderframe = new JFrame( );
                        reminderlbl = new JLabel( );
                        reminderframe.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                        remindercenter = new JPanel( );
                             reminderlbl = new JLabel( "Please type in reminder to be saved for " + buttonID + " " + monthID + " " + yearID + ":", JLabel.CENTER );
                             reminderinput = new JTextField( 30 );
                             reminderinput.setHorizontalAlignment( reminderinput.CENTER );
                             reminderinput.setEditable( true );
                             remindercenter.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                             remindercenter.add( reminderlbl );
                             remindercenter.add( reminderinput );
                        reminderbottom = new JPanel( );
                             save = new JButton( "Save" );
                             save.addActionListener( this );
                             cancel = new JButton( "Cancel" );
                             cancel.addActionListener( this );
                             dayno = new JTextField( buttonID );
                             dayno.setEditable( false );
                             dayno.setEnabled( false );
                             dayno.show( false );
                             reminderbottom.setLayout( new FlowLayout( ) );
                             reminderbottom.add( save );
                             reminderbottom.add( cancel );
                             reminderbottom.add( dayno );
                        reminderframe.setSize( 500, 75 );
                        reminderframe.add( remindercenter );
                        reminderframe.add( reminderbottom );
                        reminderframe.pack( );
                        reminderframe.show( );
              public void SaveReminder( String dayID, String yearID, String monthID ) throws Exception {
                        file = new File( "Diary.xml" );
                        doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
                        String year = yearID;
                        String month = monthID;
                        String day = dayID;
                        //System.out.println( year );
                        //System.out.println( month );
                        //System.out.println( day );
                        CreateEntry( doc.getDocumentElement( ) );
                        writeXmlFile( );
              public boolean CreateEntry( Node node ) {
                        Node searchNode;
                        searchNode = getYear( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Year" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", year );
                        node = searchNode;
                        searchNode = getMonth( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Month" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", month );
                        node = searchNode;
                        searchNode = getDay( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Day" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", day );
                        node = searchNode;
                        String entry = reminderinput.getText( );
                        Node textNode = doc.createTextNode( entry );
                        node.appendChild( textNode );
                        return true;
              private Node getYear( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if(node.getNodeName( ).equals( "Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getMonth( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getDay( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private void writeXmlFile( ) throws Exception {
                   Source source = new DOMSource( doc );
                        Result result = new StreamResult( file );
                   Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
                   xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
                   xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
                   xformer.transform( source, result );
              public void actionPerformed( ActionEvent e ) {
                        String IDButton = e.getActionCommand( );
                        String IDYear = year1.getText( );
                        Object IDMonthObj = months.getSelectedItem( );
                        if( e.getSource( ) == fetch ) {
                             String YearText = year1.getText( );
                             int YearNumber = Integer.valueOf( YearText );
                             int MonthsIndex = months.getSelectedIndex( ) + 1;
                             DrawCalendar( MonthsIndex, YearNumber );
                        else if( e.getSource( ) == cancel ) {
                             reminderframe.hide( );
                        else if( e.getSource( ) == save ) {
                             String IDDay = dayno.getText( );
                             String IDMonth = String.valueOf( IDMonthObj );
                             SaveReminder( IDDay, IDYear, IDMonth );
                        else {
                             String IDMonth = String.valueOf( IDMonthObj );
                             Toolkit.getDefaultToolkit( ).beep( );
                             int n = JOptionPane.showConfirmDialog( null, "Set reminder on this date?", "Question", JOptionPane.YES_NO_OPTION );
                             if( n == JOptionPane.YES_OPTION ) {
                                  CreateReminder( IDButton, IDYear, IDMonth );
    If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;
    import java.util.*;
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    public class CallDOM
         Document doc;
         File file;
         Scanner input;
         int year, month, day;
         String currentYear, currentMonth;
         public static void main(String args[]) throws Exception
              CallDOM cd=new CallDOM();          
         CallDOM() throws Exception
              file=new File("Diary.xml");
              //create DOM from file
              doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
              input=new Scanner(System.in);
              System.out.println("1) Create entry");
              System.out.println("2) Read entry");
              System.out.println("3) Show Diary");
              System.out.println("4) Quit");
              int choice=input.nextInt();
              while(choice!=4)
                   switch(choice)
                        case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
                        case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
                        case 3: ShowDiary(doc.getDocumentElement());
                   System.out.println("1) Create entry");
                   System.out.println("2) Read entry");
                   System.out.println("3) Show Diary");
                   System.out.println("4) Quit");
                   choice=input.nextInt();
              writeXmlFile();
         public void GetDate()
              System.out.println("Enter date (dd mm yyyy)");
              day=input.nextInt();
              month=input.nextInt();
              year=input.nextInt();
         public boolean ReadEntry(Node node)
              node = getYear(node);
              if(node==null) return false;
              node = getMonth(node);
              if(node==null) return false;
              node = getDay(node);
              if(node==null) return false;
              node = node.getFirstChild();
              while(node!=null)
                   System.out.println(node.getNodeValue().trim());     
                   node=node.getNextSibling();
              return true;               
         public boolean CreateEntry(Node node)
              Node searchNode;
              searchNode = getYear(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Year");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(year));
              node = searchNode;
              searchNode = getMonth(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Month");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(month));
              node = searchNode;
              searchNode = getDay(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Day");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(day));
              node = searchNode;
              System.out.println("Enter Text");
              String entry=input.next();
              entry+=input.nextLine();
              Node textNode = doc.createTextNode(entry);
              node.appendChild(textNode);
              return true;               
         public void ShowDiary(Node node)
              Stack<Node> stack=new Stack<Node>();
              Node child;
              stack.push(node);
              while(!stack.empty())
                   node = stack.pop();
                   if(ProcessNode(node))
                        child = node.getLastChild();
                        while(child!=null)
                             stack.push(child);
                             child = child.getPreviousSibling();
         private boolean ProcessNode(Node node)
              if(node.getNodeName().equals("Year"))
                   currentYear=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Month"))
                   currentMonth=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Day"))
                   System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
                                            currentMonth+"/"+currentYear+": ");
                   node=node.getFirstChild();
                   while(node!=null)
                        System.out.println(node.getNodeValue().trim());
                        node=node.getNextSibling();
                   return false;
              return true;               
         private Node getYear(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Year")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
                             return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getMonth(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Month")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getDay(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Day")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private void writeXmlFile() throws Exception
            Source source = new DOMSource(doc);
            Result result = new StreamResult(file);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.setOutputProperty(OutputKeys.INDENT,"yes");
            xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
            xformer.transform(source, result);
    }My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
    Thanks for any advice!!

    Since your question didn't come with any relevant details, and since you have huge steaming piles of irrelevant code, all I can give is a general answer to "Why do I need to catch this exception?"
    [url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]Exception tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

  • Could not find prepared statement with handle %.

    Greetings. I've seen several posts for this error on the web, but no clear cut answers. I captured the code below in profiler, with the intention of replaying in mgmt studio.
    However, the attempt end in the following error: "Could not find prepared statement with handle 612."
    declare @p1 int
    set @p1=612
    declare @p2 int
    set @p2=0
    declare @p7 int
    set @p7=0
    exec sp_cursorprepexec @p1 output,@p2 output,N'@P0 int,@P1 int,@P2 int,@P3 int,@P4 bit',N'EXEC dbo.mySproc @P0,@P1,@P2,@P3,@P4 ',4112,8193,@p7 output,219717,95,NULL,1,0
    select @p1, @p2, @p7
    Something noteworthy is that my sproc only has 5 input parameters, but this makes it look like it has many more.
    How do I manipulate the code enough to make it work in mgmt studio? Thanks!
    TIA, ChrisRDBA

    In profiler you would normally see RPC:Starting and RPC:Completed. The statement shown in RPC staring is what you need to pick because as Erland explained, completed would show "funky" behavior.
    Balmukund Lakhani | Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    This posting is provided "AS IS" with no warranties, and confers no rights.
    My Blog |
    Team Blog | @Twitter
    Author: SQL Server 2012 AlwaysOn -
    Paperback, Kindle

  • Why do I need to pass params. to getConnection when using OracleDataSource?

    Hi,
    I've been experimenting with Tomcat 5.5 and using Oracle proxy sessions. After many false starts, I finally have something working, but I have a question about some of the code.
    My setup:
    In <catalina_home>/conf/server.xml I have this section:
    <Context path="/App1" docBase="App1"
    debug="5" reloadable="true" crossContext="true">
    <Resource name="App1ConnectionPool" auth="Container"
    type="oracle.jdbc.pool.OracleDataSource"
    driverClassName="oracle.jdbc.driver.OracleDriver"
    factory="oracle.jdbc.pool.OracleDataSourceFactory"
    url="jdbc:oracle:thin:@127.0.0.1:1521:oddjob"
    username="app1" password="app1" maxActive="20" maxIdle="10"/>
    </Context>
    In my App directory, web.xml has:
    <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>App1ConnectionPool</res-ref-name>
    <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    And finally, my java code:
    package web;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.jdbc.driver.OracleConnection;
    import javax.naming.*;
    import java.sql.SQLException;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Properties;
    public class ConnectionPool {
    String message = "Not Connected";
    public void init() {
    OracleConnection conn = null;
    ResultSet rst = null;
    Statement stmt = null;
    try {
    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:/comp/env");
    OracleDataSource ds = (OracleDataSource) envContext.lookup("App1ConnectionPool");
    message = "Here.";
    if (envContext == null)
    throw new Exception("Error: No Context");
    if (ds == null)
    throw new Exception("Error: No DataSource");
    if (ds != null) {
    message = "Trying to connect...";
    conn = (OracleConnection ) ds.getConnection("app1","app1");
    Properties prop = new Properties();
    prop.put("PROXY_USER_NAME", "xxx/yyy");
    if (conn != null) {
    message = "Got Connection " + conn.toString() + ", ";
              conn.openProxySession(OracleConnection.PROXYTYPE_USER_NAME,prop);
    stmt = conn.createStatement();
    //rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
    rst = stmt.executeQuery("SELECT count(*) from sch_header");
    if (rst.next()) {
    message = "# of NJ schools: " + rst.getString(1);
    rst.close();
    rst = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null; // Make sure we don't close it twice
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rst != null) {
    try {
    rst.close();
    } catch (SQLException e) {
    rst = null;
    if (stmt != null) {
    try {
    stmt.close();
    } catch (SQLException e) {
    stmt = null;
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    conn = null;
    public String getMessage() {
    return message;
    My question concerns this line of code:
    conn = (OracleConnection ) ds.getConnection("app1","app1");
    Why do I need to pass in the user name/password? Other examples, that I see simply have:
    conn = (OracleConnection ) ds.getConnection();
    But when I use this code, I get the following error:
    java.sql.SQLException: invalid arguments in call
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
         at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
         at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
         at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
         at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
         at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:297)
         at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:221)
         at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:165)
         at web.ConnectionPool.init(ConnectionPool.java:32)
    ... more follows, but I trimmed to keep posting shorter :-)
    Is there anyway that I can avoid having to pass the user/password to getConnection()? It seems that I should be able to control the user/password used to establish the connection pool directly in the server.xml file and not have to supply it again in my java code. In earlier experiments when I was using "import java.sql.*" and using it's DataSource, I can use getConnection() without having to pass user/password, but then the Oracle Proxy methods don't work.
    I'm a java newbie so I guess that I should be happy that I finally figured out how to get proxy connections working. However it seems that I am missing something and I want this code to be as clean as possible.
    If anyone can point me to a better method of using connection pools and proxy sessions, I would appreciate it.
    Thanks,
    Alan

    Hi,
    Thanks for the replies.
    Avi, I'm not really sure what you are getting at with the setConnectionProperties. I looked at the javadoc and saw that I can specify user/password, but since I'm using a connection pool, shouldn't my Datasource already have that information?
    Maro, your comment about not having set the user/password for the Datasource is interesting. Are you referring to setting it in the server.xml configuration file? As you can see I did specify it in addition to setting the URL. In my code example, I'm not having to respecify the URL, but maybe I have a typo in my config file that is causing the username/password not to be read properly??
    The other weird thing is that I would have expected to see a pool of connections for user App1 in V$SESSION, but I see nothing. If I use a utility to repeatedly call a JSP page that makes use of my java example, then I do see v$session contain brief sessions for App1 and ADAVEY (proxy). The response time of the JSP seems much quicker than I would have expected if there wasn't some sort of physical connection already established though. Maybe this is just more evidence of not having my server.xml configured properly?
    Thanks.

Maybe you are looking for