CreateStatement(int, int) performance

Hi, I have some performance problems with the method createStatement(int, int) when using it on large tables (containing about 2,000,000 records). Does anyone already had the same prob?
I use the createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
The DB used is DB2/400 on IBM iSeries.
How is that method implemented? Does it fetch all elements??? Does it creates temp indexes??? I'm forced to use that method to be able to use a ResultSet.absolute(int) after...
I've read somewhere that depending on the JDBC driver, we better use a count(*) in the sql query than a ResultSet.last() then ResultSet.getRow() because the last() will fetch all records. Maybe is it the same problem?
Or maybe does anyone know if there's an equivalent of the absolute(int) in sql?
Could anyone help me to find a solution for better performances?

Indeed my question was not very clear sorry.
Here's the context :
In a web app, a user wants to make a search on client members, let's say the table has about 2,000,000 records of data.
I have to display a page navigation system, let's say the user can display 50 records by page. He must be able to navigate through page 1 to the last page back and forward and with a step of 2 or more, and he can always reach the first and last page in a single click.
That's why I used a scrollable ResultSet so I could use the rs.absolute(i) to position the cursor on the page I want to display, instead of doing rs.next() until I reach the correct position.
That system works fine as long as there's not too much records. But unfortunately, some search without any criteria can give the total table, and I'm not in position to say there must be restriction on the search. The client is king.
So I just wondered if there's a solution with good performance to doing so?
My english is not very fluent so I hope it's understable ^^

Similar Messages

  • Driver not support createStatement(int resultSetType, int resultSetConcurrency)

    I am using Weblogic 5.1 for development and would like to use resultset for
    updating
    when I call 'createStatement(int resultSetType, int resultSetConcurrency)'
    Error message prompt out that the driver does not support such method
    I am using weblogic.jdbc20.oci.Driver & weblogic.jdbc.mssqlserver4.Driver
    for testing
    Can some body help me
    regards,
    Fannie

    Right, this method is not implemented by weblogic driver. You should get a
    message like,
    "This JDBC 2.0 method is not implemented" from
    weblogic.jdbc20.oci.Connection or weblogic.jdbc20.mssqlserver4.TdsConnection
    "Fannie" <[email protected]> wrote in message
    news:3b563e73$[email protected]..
    I am using Weblogic 5.1 for development and would like to use resultsetfor
    updating
    when I call 'createStatement(int resultSetType, int resultSetConcurrency)'
    Error message prompt out that the driver does not support such method
    I am using weblogic.jdbc20.oci.Driver & weblogic.jdbc.mssqlserver4.Driver
    for testing
    Can some body help me
    regards,
    Fannie

  • ResultSet.absolute(int) Performance Issue

    I'm using the Oracle driver. I've run some tests and it appears that:
    ResultSet rs = ...;
    rs.absolute(n);
    has approximately the same performance as:
    ResultSet rs = ...;
    for (int i = 0; i < n; i++)
    rs.next();
    Is this all it is doing? For large values of "n" this could be very bad.
    I'd use "ROWNUM", but I also use an O/R framework. The only way to
    pull out specific subsets is to use JDBC scrolling. Is there anything I
    can do?
    Thanks,
    Bob

    Bob Lee wrote:
    There are at least 4 oracle driver vendors and
    multiple versions from each, so let us know
    which one you're using. See more below...I've tried the Oracle OCI (thick) and thin drivers, version 9.
    It certainly may be doing this. Very few drivers would go to the
    DBMS for each row individually, in a random access fashion.
    The driver would probably obtain and buffer all the intermediate
    rows that had not been fetched.This sucks. If I call ResultSet.absolute(), I probably don't need all of
    the intermediate rows.But you asked for them, so the driver and DBMS think you probably
    want them. Absolute() is part of implementing random access. It would
    never be interpreted as 'I don't want (some) rows'. It can be called to
    go backwards from the current position too.
    Clever SQL can be made to select the subsets (contiguous ranges) you want, one by oneDamn.It's a solution.... This sounds like something you want to do in a stored procedure.
    The cardinal performance problem in RDBMS applications is shipping scads of
    raw data out of the DBMS to the client, to be processed and/or discarded, instead
    of processing the raw stuff where it is in the DBMS.
    Good luck,
    Joe
    >
    Thanks,
    Bob
    Thanks,
    Bob

  • ResultSet.absolute(int) performance

    Hi,
    we are experiencing some horrible performance using the absolute() method on a ResultSet. I am aware Oracle only natively supports forward only cursors, but I wonder if anyone has some workaround for getting "acceptable" speeds from this method. On a local database with ~15.000 results in a rather simple query absolute() takes 5032 ms, quite a bit for a user waiting :-)
    The senario is a window with a scrollbar, the scrollbar is decoupled in the sense it's just a standard JScrollBar. The user has made a search and have maybe gotten 15.000 results, now the user wants to drag the scrollbar so it maybe ends up in what corresponds to entry 14.500 in the ResultSet. Behind the sceens we then invoke ResultSet.absolute(14500), load the data and displays it. The above mentioned ~5000 ms is unfortunately what takes the time in this operation.
    We're using Oracle 9.2.0.1.0, JDK 1.4.22_01-b06 with the thin driver found in ojdbc14.jar downloaded as newest version here from OTN. 3rd party driver suggestions are welcome but they must support somewhat complex queries across multiple table.
    Best regards
    Jan Jonasen

    Thanks for your replies. I'll look for the patch initially.
    Don't worry, we're not showing 15.000+ results at the same time :-) It's thumbnails showing images, so a user with a huge window will maybe have shown 100, but that is a bit high set. In reality it's only the result which very much like Google will contain a lot of hits, but only those which fit in the window are actually shown. Also, the reference to the scrollbar is just to simplify the example, so I'll elaborate a bit.
    A user performs a search given no arguments which results in everything from the relevant tabel in the database gets a hit, for the example of my local development one it's 15.000, customers usually have quite a bit more. In the end only whatever there's room for is extracted from the result, during "normal" circumstances this may be 25 tops, much like you would see on a search engine on the web. If the user pushes the arrow on the scrollbar, the next row for the window is loaded, again "normally" this would be maybe 5 additional results. Pressing page down/up on the comparable function of the scrollbar fills the page with the next 25 which may mean going 25 forward or backward in the original search result. Since it's a scrollbar the user can also drag in to some position, so for the example the user drags to what corresponds to 14.000 in the search result. It can somewhat be compared to Google supplying a "Go to page" in your query.
    Both going forward/backward and "jumping" to 14.000 means the usage of ResultSet.absolute(), which is as said terrible slow I guess because of forward only cursors.
    It's actually not fetching the data which takes the time, it's the usage of ResultSet.absolute(), having timed it, the call takes 5000+ ms, so I'm looking for a workaround or well, anything to help solve this slowness.
    For instance have anyone tried showing a "SELECT * FROM table" (result 10.000+) and enabled the user to jump to any row? How did you manage that?

  • Jdbc bug in executeUpdate(sql, int[]) when table name is case-sensitive;

    I have found a bug in oracle's jdbc (ojdbc6.jar), can someone tell me how to submit it so that it can be fixed?
    The BUG: using executeUpdate(insert_sql_stmt, int[]) to retrieve the generatedKey generated by before-insert trigger using a sequence results in error when the tablename is case-sensitive (but OK if table name in uppercase).
    Steps to reproduce:
    1a. create table "mixCase" (f1 integer, f2 varchar2(20));
    1b. create table upperCase (f1 integer, f2 varchar2(20));
    2a. create sequence mixCase_seq start with 1;
    2b. create sequence upperCase seq start with 1;
    3a. create or replace trigger mixCase_trigger before insert on "mixCase"
    bq. for each row \\ begin \\ select mixCase_seq.nextval into :new.f1 from dual; \\ end;
    3b. create or replace trigger upperCase_trigger before insert on upperCase
    bq. for each row \\ begin \\ select upperCase_seq.nextval into :new.f1 from dual; \\ end;
    4a. String url = "jdbc:oracle:thin:@//localhost:1521/orcl";
    bq. conn=DriverManager.getConnection(url,user,password); \\ Statement stmt = conn.createStatement (); \\ int rc=stmt.executeUpdate("insert into \"mixCase\"(f2) values('aa')",new int[]{1});
    4b. String url = "jdbc:oracle:thin:@//localhost:1521/orcl";
    bq. conn=DriverManager.getConnection(url,user,password); \\ Statement stmt = conn.createStatement (); \\ int rc=stmt.executeUpdate("insert into upperCase(f2) values('aa')",new int[]{1});
    When you run 4a or 4b in a java jdbc program:
    4b runs OK and rset=stmt.getGeneratedKeys() returns the correct f1 value of 1.
    4a results in error:
    bq. h6. java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist \\ + at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:91)+ \\ + at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)+ \\ + at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)+ \\ + at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)+ \\ + at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406)+ \\ + ...+
    +Notes:&lt;/&lt;/em&gt;
    # If Statement.RETURN_GENERATEDKEYS is used instead of "new int[]{1}" in 4b, there is no error but the rset=stmt.getGeneratedKeys() returned in a ROWID such as 'AAARUyAAEAAAAGQAAL', not what is expected. Other database's jdbc return the correct generated integer value.
    # Same 4b error if new String[]{"f1"} is used as 2nd argument for executeUpdate.
    # The only difference in 4a and 4b is that 4a has case-sensitive table name. All sequence names, trigger names, column names are implicitly deemed to be uppercase by oracle in both cases.
    bq.
    Edited by: user10343198 on Oct 2, 2008 5:50 PM
    Edited by: user10343198 on Oct 2, 2008 6:34 PM

    Please patch one fo your machines to 10.2.0.3 and then try and duplicate. You do not have to go through the complete registration of the XSD process thoguh you can check and see if the c based parser will validate on the command line using the
    schema executible under your oracle_home bin directory.
    schema 1.xml 1.xsd
    for example
    if it dupes in 10.2.0.3 open a TAR with support so that we may bug it.
    regards
    Coby

  • Delete using an int

    i hope someone can help
    here is some of my codeif (e.getSource() == yes100)
              d100.setVisible(false);
              int imp = 0;     
              try
                   imp = Integer.parseInt(itfnumber.getText());
                   catch(NumberFormatException nf){System.out.println("line 602");}
              System.out.println(imp);
              try
                   String query = "Delete from inventory where inumber = '" + imp + "'";
                   stmt = conn.createStatement();
                   int x = stmt.executeUpdate(query);
                   catch(SQLException sql){System.out.println("line 610");}
                   reset();
                   repopinventoryproduct();
    i want to delete a record from an access database i compare the data in the itfnumber (is a jtextfeild) with the data in the inumber field (a field in the access table inventory) the inumber field is set as an integer when the itfnumber is populated it is
    itfnumber.setText(String.valueOf(rs.getInt("inumber")));
    it is now set as text therefore i have to set it to an int before i make the comparision which i did (got no exception and imp printed to screen) however when i run it i get an sql exception (line 610) if anyone can help i would appreciate it

    I am not SQL expert, but why do you need quotes around a number field? I thought in sql you need quotes around string. May be that is why you are getting SQLException.

  • Error while defining :- createStatement(ResultSet.TYPE_SCROLL_SENSITIVE)

    What I am trying to do is, get the current row and compare with the previous from the resultset.
    To achieve it I am using the previous(), absolute() and next() methods from ResultSet. Now to be able to use these methods I believe I need to define connx as:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    con1 = DriverManager.getConnection("jdbc:oracle:thin:@uaix02....","....","....");
    stmt1 = con1.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE);
    By doing so when I compile from JDeveloper, I am getting the following error:
    C:\Program Files\Oracle\JDeveloper 3.2\myhtml\test548_html\untitled10.jsp
    Warning: (0) ISO-8859-1 character set may not match project compiler setting.
    Error: (82) method createStatement(int) not found in interface java.sql.Connection.
    I am importing java.sql and oracle.jdbc libraries.
    Any pointers to it would be greatly appreciated.
    Thanks in Advance
    Ajith
    null

    Fixed...
    Actually createStatement() takes zero or no arguments....
    kash! the error messages had been more developer friendly....
    Ajith

  • Help needed with project

    Hello everyone. Some help would be appreciated. I have created a wildlife resort database with access.
    It has an animals table with 5 entries, a species table with 3 entries and a user table with 3 entries.
    I have set up a JDBC-ODBC bridge.
    The server side of this application when run gets stuck upon pressing connect the first time so I have to run the server again while the first server window is running in the background and press connect for it to start running. The server works just fine after that. I can add and remove from the tables using the server.
    When I run the client and try to connect it, it doesn't accept the hostname. I can't connect or log in.
    I think the problem is with the threads but I'm not sure what to do to fix it.
    Also I use java beans for coding.
    These are some errors I get when running the client:
    java.lang.IllegalThreadStateException
    at java.lang.ThreadGroup.add(ThreadGroup.java:856)
    at java.lang.Thread.start(Thread.java:573)
    at org.apache.tools.ant.taskdefs.ProcessDestroyer.removeShutdownHook(ProcessDestroyer.java:145)
    at org.apache.tools.ant.taskdefs.ProcessDestroyer.remove(ProcessDestroyer.java:198)
    at org.apache.tools.ant.taskdefs.Execute.execute(Execute.java:487)
    at org.apache.tools.ant.taskdefs.Java.fork(Java.java:746)
    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:170)
    at org.apache.tools.ant.taskdefs.Java.execute(Java.java:83)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:377)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.Target.execute(Target.java:341)
    at org.apache.tools.ant.Target.performTasks(Target.java:369)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1214)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1062)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:217)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:236)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:125)
    Exception in thread "Thread-7" java.lang.NullPointerException
    at Client.Connect.connecting(Connect.java:45)
    at Client.ClientGUI.run(ClientGUI.java:214)
    at java.lang.Thread.run(Thread.java:595)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Client.Connect.userPass(Connect.java:206)
    at Client.ClientGUI.actionPerformed(ClientGUI.java:164)
    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.AbstractButton.doClick(AbstractButton.java:302)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
    at java.awt.Component.processMouseEvent(Component.java:5488)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
    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:1766)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
    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)
    These are the classes I have created:
    On the client side:
    //imports needed for the GUI and I/O Operations
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    public class ClientGUI extends JFrame implements ActionListener, Runnable {
    JPanel pane = new JPanel();
    //Create the Menubar Items
    JMenuBar bar = new JMenuBar();
    JMenu jMenu1 = new JMenu();
    JMenu jMenu2 = new JMenu();
    JMenu jMenu3 = new JMenu();
    JMenuItem Exit = new JMenuItem();
    JMenuItem Open = new JMenuItem();
    JMenuItem Close = new JMenuItem();
    JMenuItem Find = new JMenuItem();
    static JMenuItem Add = new JMenuItem();
    static JMenuItem Remove = new JMenuItem();
    static JMenuItem Connect1 = new JMenuItem();
    static JMenuItem Disconnect = new JMenuItem();
    static JMenuItem Login = new JMenuItem();
    static JMenuItem Logout = new JMenuItem();
    static boolean check = true;
    static JLabel running = new JLabel("You are not Connected");
    //Creates the animal JTable and adds it to a scrollpane
    public static String[] animalH = {"Id" , "Name" , "Description" , "Species Id"};
    public static Object rows1 [] [] = new Object[40][4];
    public static JTable animal = new JTable(rows1 , animalH);
    JScrollPane animalP;
    //Creates the species JTable and adds it to a scrollpane
    public static String[] speciesH = {"Species Id" , "Species Name"};
    public static Object rows2 [] [] = new Object[40][2];
    public static JTable species = new JTable(rows2 , speciesH);
    JScrollPane speciesP;
    public static Thread runner;
    //Declares Globale variables
    static int currentT;
    int respones;
    static String hostname;
    static boolean connected = false;
    /** Creates a new instance of ClientGUI */
    public ClientGUI() {
    super("SA Wildlife -- Client");
    setSize(800 , 600);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().add(running , BorderLayout.SOUTH);
    Add.setEnabled(false);
    Remove.setEnabled(false);
    Logout.setEnabled(false);
    Disconnect.setEnabled(false);
    try {
    jbInit();
    }catch(Exception e) {
    e.printStackTrace();
    addListener();
    setJMenuBar(bar);
    setVisible(true);
    //Add the actionListeners to the components
    public void addListener(){
    Open.addActionListener(this);
    Close.addActionListener(this);
    Exit.addActionListener(this);
    Connect1.addActionListener(this);
    Disconnect.addActionListener(this);
    Find.addActionListener(this);
    Login.addActionListener(this);
    Logout.addActionListener(this);
    Add.addActionListener(this);
    Remove.addActionListener(this);
    //Add the actions which the components must perform
    public void actionPerformed(ActionEvent evt){
    Object s = evt.getSource();
    if (s == Open){
    choice();
    Close();
    if (respones == 0){
    currentT = 1;
    clearTableAnimals();
    Connect.allAnimal();
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else if (respones == 1 ){
    currentT = 2;
    clearTableSpecies();
    Connect.allSpecies();
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if (s == Close){
    Close();
    }else if (s == Exit){
    exit();
    }else if (s == Connect1){
    hostname = JOptionPane.showInputDialog(null , "Please enter Hostname");
    if (check = true){
    runner = new Thread(this);
    runner.start();
    Connect1.setEnabled(false);
    Disconnect.setEnabled(true);
    }else if (s == Disconnect){
    Connect.out.println("Bye");
    runner = null;
    try {
    Connect.out.close();
    Connect.in.close();
    Connect.clientSocket.close();
    } catch (IOException ioe) {
    JOptionPane.showMessageDialog(null,
    "Error " + ioe.toString(),
    "IO Exception",
    JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    }else if (s == Find){
    choice();
    Close();
    if (respones == 0){
    currentT = 1;
    String Aname = JOptionPane.showInputDialog(null , "Enter Animal name to find ");
    clearTableAnimals();
    Connect.findAnimal(Aname);
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else{
    currentT = 2;
    String Sname = JOptionPane.showInputDialog(null , "Enter Species name to find ");
    clearTableSpecies();
    Connect.findSpecies(Sname);
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if( s== Login){
    String name = JOptionPane.showInputDialog(null , "Please enter a UserName");
    String password = JOptionPane.showInputDialog(null , "Please enter a Password");
    Connect.userPass(name , password);
    }else if (s == Logout){
    Logout();
    }else if (s== Add){
    choice();
    Close();
    if(respones == 0){
    currentT = 1;
    String id = JOptionPane.showInputDialog(null , "Enter an Animal id");
    String name = JOptionPane.showInputDialog(null , "Enter an Animal Name");
    String desc = JOptionPane.showInputDialog(null , "Enter an Animal Description");
    String speciesid = JOptionPane.showInputDialog(null , "Enter an Animal species id");
    clearTableAnimals();
    Connect.toAddAnimal(id , name , desc , speciesid);
    Connect.allAnimal();
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else{
    currentT = 2;
    String id = JOptionPane.showInputDialog(null , "Enter a Species id");
    String name = JOptionPane.showInputDialog(null , "Enter a Species name");
    clearTableSpecies();
    Connect.toAddSpecies(id , name);
    Connect.allSpecies();
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if (s == Remove){
    choice();
    Close();
    if(respones == 0){
    currentT = 1;
    String id = JOptionPane.showInputDialog(null , "Enter an Animal id to Remove");
    Connect.toRemoveAnimal(id);
    }else{
    currentT = 2;
    String id = JOptionPane.showInputDialog(null , "Enter a Species id to Remove");
    Connect.toRemoveSpecies(id);
    public void run() {
    Connect connect = new Connect();
    while (runner != null) {
    try {
    connect.connecting();
    catch (IOException ioe) {
    System.out.println("Error: " + ioe);
    ClientGUI.running.setText("You are now connected");
    //Method the creates the dialog box for the user to choose what he wants to do
    void exit(){
    String [] option = { "Exit" , "Minimize" , "Cancel" };
    int which = JOptionPane.showOptionDialog(null , "Sure you want to exit"
    , "Exiting" , 0 , JOptionPane.WARNING_MESSAGE ,
    null , option , option[2] );
    if (which == 0){
    System.exit(1);
    }else if (which == 1){
    setState(JFrame.ICONIFIED);
    }else{}
    //Closes the current table on the panel
    public void Close(){
    if(currentT == 1){
    animalP.setVisible(false);
    }else if (currentT == 2){
    speciesP.setVisible(false);
    }else{}
    //Method that give the user a choice on which table to perform actions on
    public void choice(){
    String[] choices = {"Animals" , "Species"};
    respones = JOptionPane.showOptionDialog(null ,
    "Please select Table" , "Table" , 0 , JOptionPane.INFORMATION_MESSAGE ,
    null , choices , choices[1] );
    //Clears the Species table
    public void clearTableSpecies(){
    for (int i = 0; i < 40; i++){
    rows2[0] = "";
    rows2[i][1] = "";
    //Clears the Animal table
    public void clearTableAnimals(){
    for (int i = 0; i < 40; i++){
    rows1[i][0] = "";
    rows1[i][1] = "";
    rows1[i][2] = "";
    rows1[i][3] = "";
    //Method for the Logout button
    public void Logout(){
    JOptionPane.showMessageDialog(null , "You are now logged out ");
    Login.setEnabled(true);
    Add.setEnabled(false);
    Remove.setEnabled(false);
    Logout.setEnabled(false);
    //Main Methof
    public static void main(String[] args) {
    ClientGUI GUI1 = new ClientGUI();
    // Adds all components to the panel
    private void jbInit() throws Exception {
    jMenu1.setText("File");
    Exit.setText("Exit");
    jMenu2.setText("Table Action");
    Open.setText("Open Table");
    Add.setText("Add to Table");
    Remove.setText("Remove from Table");
    Find.setText("Find In table");
    Close.setText("Close Current");
    jMenu3.setText("Client");
    Connect1.setText("Connect");
    Disconnect.setText("Disconnect");
    Login.setText("Login");
    Logout.setText("Logout");
    bar.add(jMenu1);
    bar.add(jMenu2);
    bar.add(jMenu3);
    jMenu1.add(Exit);
    jMenu2.add(Open);
    jMenu2.add(Add);
    jMenu2.add(Remove);
    jMenu2.add(Find);
    jMenu2.add(Close);
    jMenu3.add(Connect1);
    jMenu3.add(Disconnect);
    jMenu3.add(Login);
    jMenu3.add(Logout);
    package Client;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.util.*;
    public class Connect {
    static public Socket clientSocket = null;
    static public PrintWriter out = null;
    static public BufferedReader in = null;
    public void connecting() throws IOException {
    try{
    clientSocket = new Socket(ClientGUI.hostname , 1234);
    out = new PrintWriter(clientSocket.getOutputStream() , true);
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }catch (UnknownHostException e){
    JOptionPane.showMessageDialog(null , "Dont know about host");
    ClientGUI.check = false;
    ClientGUI.Connect1.setEnabled(true);
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.runner = null;
    }catch(IOException i){
    ClientGUI.check = false;
    JOptionPane.showMessageDialog(null,"Couldnt get i/O for the connection to 127.0.0.0.1");
    ClientGUI.Connect1.setEnabled(true);
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.runner = null;
    if (ClientGUI.check = true){
    String fromServer;
    StringTokenizer token1;
    String First;
    String Second;
    String Third;
    while ( (fromServer = in.readLine()) != null) {
    System.out.println("From SerVer ---------------> " + fromServer);
    token1 = new StringTokenizer(fromServer, "%");
    StringTokenizer token2;
    StringTokenizer token3;
    First = token1.nextToken();
    System.out.println("First ------- > " + First);
    if (First.equalsIgnoreCase("SelectedAnimal")) {
    System.out.println("IT's ON ");
    Second = token1.nextToken();
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In the 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In the 2while");
    token3 = new StringTokenizer(token2.nextToken(), "@");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows1[y][x] = token3.nextToken();
    x++;
    y++;
    else if (First.equalsIgnoreCase("SelectedSpecies")) {
    System.out.println("IT's ON BITCH ");
    Second = token1.nextToken();
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In die 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In die 2while");
    token3 = new StringTokenizer(token2.nextToken(), "@");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows2[y][x] = token3.nextToken();
    x++;
    y++;
    else if (First.equalsIgnoreCase("FoundAnimal")) {
    Second = token1.nextToken();
    if (! (Second.equalsIgnoreCase("NONE"))) {
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In the 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In the 2while");
    token3 = new StringTokenizer(token2.nextToken(), "#@#");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows1[y][x] = token3.nextToken();
    x++;
    y++;
    else {
    JOptionPane.showMessageDialog(null,
    "Could not find Animal , Please try again");
    else if (First.equalsIgnoreCase("FoundSpecies")) {
    Second = token1.nextToken();
    if (! (Second.equalsIgnoreCase("NONE"))) {
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In die 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In die 2while");
    token3 = new StringTokenizer(token2.nextToken(), "#@#");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows2[y][x] = token3.nextToken();
    x++;
    y++;
    else {
    JOptionPane.showMessageDialog(null,
    "Could not find Species , Please try again");
    else if (First.equalsIgnoreCase("FoundUser")) {
    System.out.println("From Server --- > " + First);
    String login = token1.nextToken();
    System.out.println("Find true or false ---- > " + login);
    if (login.equalsIgnoreCase("isUser")) {
    JOptionPane.showMessageDialog(null, "You are now logged in");
    ClientGUI.Add.setEnabled(true);
    ClientGUI.Remove.setEnabled(true);
    ClientGUI.Logout.setEnabled(true);
    ClientGUI.Login.setEnabled(false);
    else {
    JOptionPane.showMessageDialog(null,
    "Invalid Username or Password, Please try again");
    else if (First.equalsIgnoreCase("RecordAddedA")) {
    JOptionPane.showMessageDialog(null, "Record Added");
    else if (First.equalsIgnoreCase("RecordAddedS")) {
    JOptionPane.showMessageDialog(null, "Record Added");
    else if (First.equalsIgnoreCase("SQLE")) {
    System.out.println("ERROR SQL ERROR");
    else if (First.equalsIgnoreCase("Blah1")) {
    System.out.println("ERROR Ander ERROR");
    else if (First.equalsIgnoreCase("AnimalRemoved")) {
    JOptionPane.showMessageDialog(null, "Record Removed");
    else if (First.equalsIgnoreCase("SpeciesRemoved")) {
    JOptionPane.showMessageDialog(null, "Record Removed");
    }else{
    System.out.println("BLAAAAAAAAH");
    static public void Close() throws IOException{
    out.println("bye");
    ClientGUI.runner = null;
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.Connect1.setEnabled(true);
    out.close();
    in.close();
    clientSocket.close();
    static public void allAnimal(){
    out.println("SELECTANIMALS");
    static public void allSpecies(){
    out.println("SELECTSPECIES");
    static public void findAnimal(String name){
    out.println("FINDANIMAL" + "@" + name);
    static public void findSpecies(String name){
    out.println("FINDSPECIES@" + name);
    static public void userPass(String name , String password){
    System.out.println("FINDUSER -----> " + name + " " + password);
    out.println("FINDUSER@" + name + "@" + password);
    static public void toAddAnimal(String id , String name , String desc , String species){
    out.println("toAddAnimal@" + id +"@" + name +"@" + desc +"@" + species );
    static public void toAddSpecies(String id , String name){
    out.println("toAddSpecies@" + id +"@" + name );
    static public void toRemoveAnimal(String id){
    out.println("toRemoveAnimal@" + id);
    static public void toRemoveSpecies(String id){
    out.println("toRemoveSpecies@" + id);
    On the server side:
    package Server;
    ////import everything necesary for the Database Connection
    import java.sql.*;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.util.*;
    public class DatabaseConnect {
    //Declaration of Globale variables
    static int hoeveel = 0;
    static ResultSet rec ;
    static String bidData[] = new String[100];
    static String toSend[] = new String[100];
    //Connects the program to the database
    public DatabaseConnect() {
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    }catch(ClassNotFoundException cnf){
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    System.out.println("SqlExeption" + se);
    //Selects the data from the databas and adds the data to the tables
    public void open(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    if (ServerGUI.currentT == 1){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM ANIMALS");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" +
    rec.getString(2) + "@#@" +
    rec.getString(3) + "@#@" +
    rec.getString(4);
    readintoTable1();
    }else if (ServerGUI.currentT == 2){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM SPECIES");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" + rec.getString(2);
    readintoTable2();
    }else if(ServerGUI.currentT == 3){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM USER");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" + rec.getString(2)
    + "@#@" + rec.getString(3);
    readintoTable3();
    }catch(ClassNotFoundException cnf){
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    System.out.println("SqlExeption" + se);
    //Clean the table and reads the data into the animal table
    public void readintoTable1(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows1[a][0] = "";
    ServerGUI.rows1[a][1] = "";
    ServerGUI.rows1[a][2] = "";
    ServerGUI.rows1[a][3] = "";
    for (int i = 0; i < hoeveel; i++) {
    StringTokenizer str = new StringTokenizer(bidData[i], "@#@");
    ServerGUI.rows1[i][0] = str.nextToken();
    ServerGUI.rows1[i][1] = str.nextToken();
    ServerGUI.rows1[i][2] = str.nextToken();
    ServerGUI.rows1[i][3] = str.nextToken();
    //Clean the table and reads the data into the Species table
    public void readintoTable2(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows2[a][0] = "";
    ServerGUI.rows2[a][1] = "";
    for (int i = 0; i < hoeveel; i++) {
    StringTokenizer str = new StringTokenizer(bidData[i], "@#@");
    ServerGUI.rows2[i][0] = str.nextToken();
    ServerGUI.rows2[i][1] = str.nextToken();
    //Clean the table and reads the data into the User table
    public void readintoTable3(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows3[a][0] = "";
    ServerGUI.rows3[a][1] = "";
    ServerGUI.rows3[a][2] = "";
    for (int b = 0; b < hoeveel; b++) {
    StringTokenizer str = new StringTokenizer(bidData, "@#@");
    ServerGUI.rows3[b][0] = str.nextToken();
    ServerGUI.rows3[b][1] = str.nextToken();
    ServerGUI.rows3[b][2] = str.nextToken();
    //add animal information to the Animal table in the database
    public void addAnimal(String id , String name , String desc , String species_id){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO animals" + "(animal_id, animal_Name , description , species_id)" +
    "VALUES (" + id + ", '" + name + "', '" + desc + "', " + species_id + ")";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshAnimal();
    ServerGUI.currentT = 1;
    open();
    }catch(ClassNotFoundException cnf){
    JOptionPane.showMessageDialog(null,
    "Class Not Found -> " + cnf.toString(),
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    JOptionPane.showMessageDialog(null,
    "SQL Exception -> " + se.toString()
    + "\n Please make sure all data is entered correctly ",
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("SqlExeption" + se);
    //add animal information to the Species table in the database
    public void addSpecies(String id1 , String name1){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO species" + "(species_id, species_name)" +
    "VALUES ( '" + id1 + "', '" + name1 + "')";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshSpecies();
    ServerGUI.currentT = 2;
    open();
    }catch(ClassNotFoundException cnf){
    JOptionPane.showMessageDialog(null,
    "Class Not Found -> " + cnf.toString(),
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    JOptionPane.showMessageDialog(null,
    "SQL Exception -> " + se.toString()
    + "\n Please make sure all data is entered correctly ",
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("SqlExeption" + se);
    //add animal information to the User table in the database
    public void addUser(String id2 , String user , String pass){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO user" + "(user_id, user_name ,user_password)" +
    "VALUES ( '" + id2 + "', '" + user + "', '"+ pass + "')";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshUser();
    ServerGUI.currentT = 3

    Your code is completely unreliable and it should be placed inside a code block when you add it. Also your question would be better off in the JDBC forum than the networking one.

  • Not able to run a JSP file in Tomcat 5.5

    Hello friends i am new to JSP programming.
    I recently designed a application to enter values of certain field in a database (Using SQL Server Database)
    i used a file name Register.jsp, so when the action is performed by clicking submit button it use to call another file named Register_DB.jsp in which database insertion is performed this 2nd file includes another .java file which is actually creating the JDBC ODBC connection drivers
    but whenever i use to run the programme using tomcat-5.5 i use to get certain error as below ------------------->
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to load class for JSP
         org.apache.jasper.JspCompilationContext.load(JspCompilationContext.java:591)
         org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:137)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:305)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.ClassNotFoundException: org.apache.jsp.Registration_jsp
         java.net.URLClassLoader$1.run(Unknown Source)
         java.security.AccessController.doPrivileged(Native Method)
         java.net.URLClassLoader.findClass(Unknown Source)
         org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:158)
         org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:71)
         org.apache.jasper.JspCompilationContext.load(JspCompilationContext.java:589)
         org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:137)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:305)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
    Apache Tomcat/5.5.9***********************************************************************************************************
    So can anybody tell me what should i do to resolve this error
    here is the code what i have written
    File Name Registration.jsp
    <!--     *****     File Name Test.jsp     *****     -->
    <%@ import="Login.connectionBean" %>
    <%@ language="java" %>
    <%@ import="java.io.*" %>
    <%@ import="java.sql.*" %>
    <%@ import="javax.sql.*" %>
    <jsp:useBean id="sq" scope="page" class="Login.connectionBean" type="connectionBean"/>
         <jsp:setProperty name="sq" property="*"/>
    <html>
    <!-- DW6 -->
         <head>
              <!-- Copyright 2005 Macromedia, Inc. All rights reserved. -->
              <title>Registration Form</title>
         </head>
         <body>
              <form name="Test" action="Registration_DB.jsp" method="get">
                   <table width="100%" border="0">
                     <tr>
                        <td colspan="5"></td>
                     </tr>
                     <tr>
                        <td width="10%" height="250"></td>
                        <td width="90%" colspan="4"><div align="center">
                          <table width="437" border="1">
                               <tr>
                                  <td><div align="center">User ID </div></td>
                                  <td> </td>
                                  <td><div align="center">
                                         <input name="User_ID" type="text" size="25" maxlength="25" />
                                  </div></td>
                               </tr>
                               <tr>
                                  <td><div align="center"></div></td>
                                  <td> </td>
                                  <td><div align="center"></div></td>
                               </tr>
                               <tr>
                                  <td width="149"><div align="center">User name </div></td>
                                  <td width="27"> </td>
                                  <td width="239"><div align="center">
                                       <input name="User_Name" type="text" size="25" maxlength="25" />
                                  </div></td>
                               </tr>
                               <tr>
                                  <td><div align="center"></div></td>
                                  <td><div align="center"></div></td>
                                  <td><div align="center"></div></td>
                               </tr>
                               <tr>
                                  <td><div align="center">Password</div></td>
                                  <td> </td>
                                  <td><div align="center">
                                        <input name="Password" type="text" size="25" maxlength="25" />
                                       </div>
                                  </td>
                               </tr>
                               <tr>
                                  <td><div align="center"></div></td>
                                  <td> </td>
                                  <td><div align="center"></div></td>
                               </tr>
                               <tr>
                                  <td><div align="center">
                                    <input name="Button_Reset" type="reset" value="Reset Fields" />
                                  </div></td>
                                  <td> </td>
                                  <td><div align="center">
                                       <input name="Button_Submit" type="reset" value="Submit Details" />
                                                   <%
              String User_Id=request.getParameter("User_Id")
              String User_Name="";
              String Password="";
              %>
              <%
              try
              sq.connect();
              if(user_Id!==null && User_Id!="")
              ResultSet rs2.sq.execQuery("select User_Name FROM User_Login where User_Id='"+User_Id+"'");
              catch(Exception e)
                   out.println("Exception Caught" +e);
                   e.printStackTrace();
              %>
                                       </div></td>
                               </tr>
                               </table>
                        </div></td>
                     </tr>
                   </table>
              </form>
         </body>
    </html>***********************************************************************************************************
    File Name Registration_DB.jsp
    <!--     *****     File Name Test_DB.jsp     *****     -->
    <%@ language="java" %>
    <%@ import="Login.connectionBean" %>
    <%@ import="java.sql.*" %>
    <%@ import="javax.sql.*" %>
    <%@ import="java.io.*" %>
    <jsp:useBean id="sq" scope="page" class="Login.connectionBean" type="connectionBean"/>
         <jsp:setProperty name="sq" property="*"/>
    <html>
         <head>
              <title>Untitled Document</title>
         </head>
    <body>     
              <%
              String Button_Submit = request.getParameter("Button_Submit");
              String User_Id = request.getParameter("User_Id");
              String User_Name = request.getParameter("User_Name");
              String Password = request.getParameter("Password");
              %>
              <%!
              ResultSet rs1=null;
              ResultSet rs2=null;
              %>
              <%
              try
                   sq.connect();
                   if(Button_Submit!=null && Button_Submit!="")
                        String qry="INSERT INTO User_Login (User_Id, User_Name, Password) VALUES('"+User_Id+"','"+User_Name+"','"+Password+"')";
                        int i=sq.executeUpdae(qry);
                        if (i>0)
                             response.sendRedirect("Registration.jsp");
              catch(Exception e)
                   out.println("Exception Caught" +e);
                   e.printStackTrace();
    %>
         </body>
    </html>***********************************************************************************************************
    File name connectionBean.java
    package Login;
    import java.sql.*;
    public class connectionBean
         private Connection con;
         public connectionBean()
              super();
         public boolean connect() throws ClassNotFoundException, SQLException
               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
               con=DriverManager.getConnection("jdbc:odbc:JAVA"," "," ");
               return true;
         public void close() throws SQLException
              con.close();
         public ResultSet execQuery(String qry) throws SQLException
              Statement stmt=con.createStatement();
              ResultSet rs=stmt.executeQuery(qry);
              return(rs==null)?null:rs;
         public int execUpdae(String qry) throws SQLException
              Statement stmt=con.createStatement();
              int i=stmt.executeUpdate(qry);
              return(i==0)?0:i;
    }

    hi
    here the problem is tat the server culdnt find the class for u page,
    check u hav deployed it properly or not,
    check the tomcat installation and is it working fine,
    regards
    venkat

  • Why is the second row in the recordset not updated?

    Hi,
    I have this problem.
    I have written a servlet named processPOItem.
    The following is the doPost Method in the processPOItem class:
    public class processPOItem extends HttpServlet {
    //attributes
    public String strPO;
    ConnectionPool connectionPool = null;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
            int counter=0, remainder=0;
            String SearchPOItems;
            String strStatus, ISBN;
            String price;
            response.setContentType("text/html"); //html output
            PrintWriter out = response.getWriter();
            //get the parameter named PO
            strPO = request.getParameter("PO");
            Connection dbConn = null;
            try{  
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Purchase Order " + strPO + "</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<table width=600 border=0 align=center>");
                out.println("<tr>");
                out.println("<td colspan=4 align=center>");
                out.println("<font face=Arial size=2>");
                out.println("<b>Purchase Order: " + strPO + "</b>");
                out.println("</font>");
                out.println("</td>");
                out.println("</tr>");
                out.println("</table>");
                out.println("<form method=post action=processPOItem>");
                out.println("<input name=updatePO type=hidden value=1>");  
                out.println("<table width=800 border=0 cellspacing=1 cellpadding=0 align=center>");
                out.println("<tr bgcolor=\"#990000\">"); //Display the mb_PurchaseItem
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">No</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">ISBN</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">Title</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">Status</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">Quantity</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">Unit Price</font></b></td>");
                out.println("<td align=center><b><font size=1 face=Verdana color=\"#FFFFFF\">Delivered Date</font></b></td>");
                out.println("</tr>");
                //get the SQL statement
                SearchPOItems = searchSQL(strPO);
                //get free connection from Pool
                dbConn = connectionPool.getConnection();
                //create a statement object
                Statement stmt = dbConn.createStatement();
                //create the recordset
                ResultSet rs = stmt.executeQuery(SearchPOItems);
                //display the recordset
                while (rs.next())
                    counter++;
                    remainder = counter % 2;
                    if (remainder == 0)
                       out.println("<tr bgcolor=\"#C1C1C1\">");
                    else
                       out.println("<tr bgcolor=\"#E1E1FF\">");
                    //Display the individual Purchase item under the customer
                    out.println("<td align=center><font size=1 face=Verdana>" + counter + "</font></td>");
                    ISBN = rs.getString("mb_ISBN");
                    out.println("<td align=center><font size=1 face=Verdana>" + ISBN + "</font></td>");
                    out.println("<td align=center><font size=1 face=Verdana>" + rs.getString("mb_Title") + "</font></td>");
                    strStatus = rs.getString("mb_Status");
                    out.println("<td align=center><font size=1 face=Verdana>");
                    out.println("<select name=\"mb_Status" + ISBN + "\">");
                    out.println("<option value=PENDING");
                    if (strStatus.equals("PENDING"))
                       out.println("selected>Pending</option>");
                    else  
                       out.println(">Pending</option>");
                    out.println("<option value=PROCESSING");
                    if (strStatus.equals("PROCESSING"))
                       out.println("selected>Processing</option>");
                    else  
                       out.println(">Processing</option>");               
                    out.println("<option value=DELIVERED");
                    if (strStatus.equals("DELIVERED"))
                       out.println("selected>Delivered</option>");
                    else  
                       out.println(">Delivered</option>");
                    out.println("<option value=CANCELLED");
                    if (strStatus.equals("CANCELLED"))
                       out.println("selected>Cancelled</option>");
                    else  
                       out.println(">Cancelled</option>");
                    out.println("</select>");
                    out.println("</font>");      
                    out.println("</td>");
                    out.println("<td align=center><font size=1 face=Verdana>" + rs.getString("mb_Qty") + "</font></td>");
                    /*price = rs.getString("mb_Price");
                    NumberFormat moneyAmount = NumberFormat.getCurrencyInstance();
                    Double dPrice = Double.parseDouble(price);
                    out.println("<td align=center><font size=1 face=Verdana>" + rs.getString("mb_Price") + "</font></td>");
                    out.println("<td align=center colspan=2><font size=1 face=Verdana>");
                    if (strStatus.equals("DELIVERED"))
                        //status = "DELIVERED"
                        out.println("<input align=center name=\"deliveredDate" + ISBN + "\" type=text size=10 maxlength=10 value=" + rs.getString("mb_DeliveredDate") + ">");    
                    else
                        out.println("<input align=center name=\"deliveredDate" + ISBN + "\" type=text size=10 maxlength=10 value=Nil disabled>");
                    out.println("</font>");   
                    out.println("</td>");
                    out.println("</tr>");
                out.println("<tr><td> </td></tr>");
                out.println("<TR>");
                out.println("<TD colspan=3 align=center>");
                out.println("<INPUT TYPE=submit BORDER=1 value=update name=update>");
                out.println("</td>");
                out.println("<TD colspan=3 align=center>");
                out.println("<a href=\"javascript:window.close()\"><img src=\"Close.gif\" BORDER=0></a>");
                out.println("</td>");
                out.println("</tr>");
                out.println("<tr>");
                rs.close();  
                stmt.close();
                out.println("</form>");
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
                out.close();
            catch (Exception e)
                //sendErrorToClient(out, e); //send stack trace to client
                System.out.println(e.getMessage());
            finally{
                //return connection to Pool
                connectionPool.returnConnection(dbConn);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
               response.setContentType("text/html"); //html output
               PrintWriter out = response.getWriter();
               Connection dbConn = null;
               //get the parameters posted back by processPOItem servlet
               String processingAll = request.getParameter("processingAll");
               String deliveredAll = request.getParameter("deliveredAll");
               String deliveredDate = request.getParameter("deliveredDate");
               String refInvoice = request.getParameter("refInvoice");
               String refNumber = request.getParameter("refNumber");
               //String status = request.getParameter("status");  
               //check if update button is pressed
               String updatePO = request.getParameter("updatePO");
               //sql statement variable
               String sqlUpdatePOStatus;
               String isbn, poItemStatus;
               //update button was pressed
               if (!updatePO.equals(""))
                try{
                    //get the SQL statement
                    String SearchPOItems = searchSQL(strPO);
                    //get free connection pool
                    dbConn = connectionPool.getConnection();
                    //create a statement object
                    Statement stmt = dbConn.createStatement();
                    //create the recordset
                    ResultSet rs = stmt.executeQuery(SearchPOItems);
                    int index = 0;
                    //display the recordset
                    while (rs.next())
                      isbn = rs.getString("mb_ISBN");
                      poItemStatus = request.getParameter("mb_Status" + isbn);
                      out.println(isbn + " " + poItemStatus);
                      out.println("<br>");
                      //update the status of individual PO item
    if (!poItemStatus.equals(""))
    sqlUpdatePOStatus = updatePOItemSQL(strPO, isbn, poItemStatus);
    stmt.executeUpdate(sqlUpdatePOStatus);
                    rs.close();  
                    stmt.close();
                    out.close();
                catch (Exception e)
                    System.out.println(e.getMessage());
                finally{
                        //return connection to pool
                        connectionPool.returnConnection(dbConn);
    }When I perform a form submit in my doGet() method, the doPost Method() responsed. However, it encounter error in updating the second row in the recordset as highlighted in bold.
    After the first row is updated. The second row did not get updated at all.
    The error return was "Resultset is closed".
    What actually is wrong? How can I execute a sqlstatement inside a recordset? How to solve this problem?

    Did you turn on the "updatable" switch for the result
    set?
    public Statement createStatement(int resultSetType,
    int resultSetConcurrency) throws
    SQLException
    Parameters:
    resultSetType - a result set type; see
    ResultSet.TYPE_XXX
    resultSetConcurrency - a concurrency type; see
    ResultSet.CONCUR_XXX
    static int CONCUR_UPDATABLE
    JDBC 2.0 The concurrency mode for a ResultSet object
    that may be updated.Hi,
    do you refer to the following change of code:
    //create a statement object (original)
    Statement stmt = dbConn.createStatement();change to the following:
    //create a statement object (original)
    Statement stmt = dbConn.createStatement(resultSetType,
    resultSetConcurrency);when I use another statement object for executeupdate, what I got was the connection was used by another hstmt. Thus the second column was not updated at all.
    Why?

  • Java DataBase in NetBeans!!

    Hi there,
    can you help guy,
    I have the NetBeans IDE 4.1,
    Oracle 9,
    j2sdk1.4.0,
    and win xp (on standalone machine)
    I remember the old version of NetBeans, you can use Mounting FileSystem for jdbc\oracle\driver
    to use the OracleDriver
    but I get message error at compiler says that package jdbc.oracle.driver does not exist
    please I need help in who to do Mounting FileSystem or other way
    here is my code of java
    // Database application using Oracle and Java programming Language
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import jdbc.sql.*
    import java.awt.*;
    public class OracleJavaCustomerWindow extends JFrame
    private JLabel labelCId,labelCName,labelCCity,labelCPhone;
    private JTextField textCId,textCName,textCCity,textCPhone;
    private JPanel labelPanel,buttonPanel,textAreaPanel,labelTextAreaPanel;
    private JTextArea outputArea;
    private JScrollPane scrollPane;
    private JButton buttonDisplay,buttonAdd,buttonModifyRecord,buttonUpdate,buttonDelete;
    private JButton buttonClear;
    private JTextField field1,field2,field3,field4;
    private JLabel label1,label2,label3,label4;
    private JPanel mixedPanel,mixedPanel2,fieldPanel1,fieldPanel2,fieldPanel3,fieldPanel4;
    static Connection sqlconn = null;
    // set up GUI with constrictor(IT IS A METHOD. EACHO CLASS AT LEST HAVE ONE)
    public OracleJavaCustomerWindow ()
    super("Display Oracle Data for Customers");
    try{
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
              sqlconn= DriverManager.getConnection ("jdbc:oracle:oci:@Kawasaki", "scott", "tiger");
    catch(SQLException ex)
    System.out.println("SQLException:" + ex.getMessage() + "<BR>");     
    // add GUI components to container
    Container container = getContentPane();
    container.setLayout(new FlowLayout(FlowLayout.CENTER));
    // Build labelPanel
    labelCId = new JLabel(" Customer ID");
    labelCName = new JLabel("Customer Name");
         labelCCity = new JLabel("Customer City");
    labelCPhone = new JLabel("Customer Phone");
    labelPanel = new JPanel();
    labelPanel.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
         labelPanel.add(labelCId);
    labelPanel.add(labelCName);
    labelPanel.add(labelCCity);
    labelPanel.add(labelCPhone);
    // Build textAreaPanel
    outputArea = new JTextArea(10,30);
    outputArea.setEditable(false);
    scrollPane = new JScrollPane(outputArea);
    textAreaPanel = new JPanel();
    textAreaPanel.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
    textAreaPanel.add(scrollPane);
    // Build labelTextAreaPanel which contains labelPanel and textAreaPanel
    // to be ready for adding to container
    labelTextAreaPanel= new JPanel();
    labelTextAreaPanel.setLayout(new BorderLayout());
    labelTextAreaPanel.add(labelPanel,BorderLayout.NORTH);
    labelTextAreaPanel.add(textAreaPanel,BorderLayout.SOUTH);
    // Buld buttonPanel
    buttonDisplay = new JButton ("Display Table");
    buttonClear = new JButton ("Clear");
    buttonAdd = new JButton("Add New Record");
    buttonUpdate= new JButton("Display Record");
    buttonModifyRecord = new JButton("Modify Record");
    buttonDelete = new JButton("Delete Record");
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(6,1,10,5));
    buttonPanel.add(buttonAdd);
    buttonPanel.add(buttonUpdate);
    buttonPanel.add(buttonModifyRecord);
    buttonPanel.add(buttonDisplay);
    buttonPanel.add(buttonDelete);
    buttonPanel.add(buttonClear);
    // build fieldPanel1
    label1 = new JLabel("Customer Number");
    field1 = new JTextField(10);
    fieldPanel1 = new JPanel();
    fieldPanel1.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
    fieldPanel1.add(label1);
    fieldPanel1.add(field1);
    // build fieldPanel2
    fieldPanel2 = new JPanel();
    label2 = new JLabel("Customer Name");
    field2 = new JTextField(10);
    fieldPanel2.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
    fieldPanel2.add(label2);
    fieldPanel2.add(field2);
    // build fieldPanel3
    fieldPanel3 = new JPanel();
    label3 = new JLabel("Customer City");
    field3 = new JTextField(10);
    fieldPanel3.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
    fieldPanel3.add(label3);
    fieldPanel3.add(field3);
         // build fieldPanel4
    fieldPanel4 = new JPanel();
    label4 = new JLabel("Customer Phone");
    field4 = new JTextField(10);
    fieldPanel4.setLayout(new FlowLayout(FlowLayout.CENTER,3,5));
    fieldPanel4.add(label4);
    fieldPanel4.add(field4);
    // Build mixedPanel which contains fieldPanel1, fieldPanel2,fieldPanel3
    // to be ready for adding to container
    mixedPanel = new JPanel();
    mixedPanel.setLayout(new BorderLayout());
         mixedPanel.add(fieldPanel1,BorderLayout.NORTH);
    mixedPanel.add(fieldPanel2,BorderLayout.CENTER);
    mixedPanel.add(fieldPanel3,BorderLayout.SOUTH);
    mixedPanel2 = new JPanel();
    mixedPanel2.add(fieldPanel4,BorderLayout.SOUTH);
    // add all panels to the container
    container.add(mixedPanel);
    container.add(mixedPanel2);
    container.setBackground(Color.DARK_GRAY);
    container.add(labelTextAreaPanel);
         container.add(buttonPanel);
    //--------- Messages to communicate with different objects
    //----------- method to clear the outputarea
    buttonClear.addActionListener(
              // anonymous inner class
    new ActionListener()
    public void actionPerformed(ActionEvent event)
                        outputArea.setText("");
    }// actionPerformed
    }// anonymous inner class
    //--------- method to use button event--------------------
    buttonDisplay.addActionListener(
    //anonymous class
    new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        //Connection sqlca = null;
                   Statement sqlStatement = null;
                   ResultSet rset = null;
                   try{
                             //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                             //sqlca= DriverManager.getConnection ("jdbc:oracle:thin:@dbserver:1521:infs", "manzur", "manzur");
                             sqlStatement = sqlconn.createStatement ();
                             rset = sqlStatement.executeQuery ("select * from customers");
                             while (rset.next ()){
                                  String CUSTOMERID=rset.getObject(1).toString();
                                  String CUSTOMERNAME =rset.getObject(2).toString();
                                  String CUSTOMERCITY =rset.getObject(3).toString();
    String CUSTOMERPHONE =rset.getObject(4).toString();
                                  //String map=rset.getObject(4).toString();
                                  //String region=rset.getObject(5).toString();
                                  //System.out.println (id + "\t" + name + "\t" + loc );
                   outputArea.append(CUSTOMERID + "\t" + CUSTOMERNAME + "\t" + CUSTOMERCITY + "\t" + CUSTOMERPHONE + "\n" );
                             } // end while
                        }// end try
                        catch (SQLException ex)
                             System.out.println("SQLException:" + ex.getMessage() + "<BR>");
                        }// catch
    }// action performed
    } // anonymous inner class
    );// end addActionListener
    // ------ method to add Customers to the database
         buttonAdd.addActionListener(
         // anonymous inner class
    new ActionListener()
    public void actionPerformed(ActionEvent event)
    try{
                   Statement sqlStatement = null;
    ResultSet rtbookset = null;
    // create statement
    sqlStatement = sqlconn.createStatement();
    int CUSTOMERID = Integer.parseInt(field1.getText());
    String CUSTOMERNAME = field2.getText();
                   String CUSTOMERCITY = field3.getText();
    int CUSTOMERPHONE = Integer.parseInt(field4.getText());
              // create query
                   String insertquery = "INSERT INTO CUSTOMERS VALUES("
         + CUSTOMERID + "," + "'" + CUSTOMERNAME + "'," + "'" + CUSTOMERCITY + "'," + CUSTOMERPHONE + ")";
              // execute the query
                             sqlStatement.executeQuery(insertquery);
                             // clear the textfields
                             field1.setText("");
                             field2.setText("");
                             field3.setText("");
    field4.setText("");
              JOptionPane.showMessageDialog(null,"Record added");                     
    }// try
    catch(SQLException ex)
                        System.out.println("Record exists :" + ex.getMessage() + "<BR>");
                   }// catch
    }// actionPerformed
    }// anonymous inner class
    //--------- method to use buttonUpdate event--------------------
    buttonUpdate.addActionListener(
    //anonymous class
    new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        //Connection sqlconn = null;
                   Statement sqlStatement = null;
                   ResultSet rset = null;
    int CUSTOMER_ID = Integer.parseInt(field1.getText());
                   try{
                             //int CUSTOMER_ID = Integer.parseInt(field1.getText());
              //String d_name = field2.getText();
                             //String d_loc = field3.getText();
                             //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                             //sqlca= DriverManager.getConnection ("jdbc:oracle:thin:@dbserver:1521:infs", "manzur", "manzur");
                             sqlStatement = sqlconn.createStatement ();
                             rset = sqlStatement.executeQuery ("select * from CUSTOMERS where CUSTOMER_ID =" + CUSTOMER_ID);
                             rset.next ();
                             //int id=rset.getInt("DEPTNO");
                             String CUSTOMERID = rset.getObject(1).toString();          
                             String CUSTOMERNAME=rset.getString("CUSTOMER_NAME");
                             String CUSTOMERCITY=rset.getString("CUSTOMER_CITY");
    String CUSTOMERPHONE=rset.getString("CUSTOMER_PHONE");
    field1.setText(CUSTOMERID);
                             field2.setText(CUSTOMERNAME);
                             field3.setText(CUSTOMERCITY);
    field4.setText(CUSTOMERPHONE);
    //buttonUpdate.setEnabled(false);
    //buttonModifyRecord.setEnabled(true);
    //rset.close();
                        }// end try
                        catch (SQLException ex)
                             JOptionPane.showMessageDialog(null,"No Record found with CUSTOMER ID :" + CUSTOMER_ID );
                             //System.out.println("SQLException:No record found" + ex.getMessage() + "<BR>");
                        }// catch
    }// action performed
    } // anonymous inner class
    );// end addActionListener
    //---------Method to modify record------------------------------------
    buttonModifyRecord.addActionListener(
    //anonymous class
    new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        //Connection sqlconn = null;
                   Statement sqlStatement = null;
                   ResultSet rset = null;
                   try{
                             //int dept_no = Integer.parseInt(field1.getText());
              //String d_name = field2.getText();
                             //String d_loc = field3.getText();
                             //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                             //sqlca= DriverManager.getConnection ("jdbc:oracle:thin:@dbserver:1521:infs", "manzur", "manzur");
                             sqlStatement = sqlconn.createStatement ();
    int CUSTOMERID = Integer.parseInt(field1.getText());
              String CUSTOMERNAME = field2.getText();
                             String CUSTOMERCITY = field3.getText();
    int CUSTOMERPHONE = Integer.parseInt(field4.getText());
                             String updatequery = "UPDATE CUSTOMERS SET CUSTOMER_NAME = " + "'" + CUSTOMERNAME + "',"
    + " CUSTOMER_CITY = " + "'" + CUSTOMERCITY + "'," + " CUSTOMER_PHONE = " + CUSTOMERPHONE
    + " Where CUSTOMER_ID = " + CUSTOMERID;
              // execute the query
                             sqlStatement.executeQuery(updatequery);
                             // clear the textfields
                             field1.setText("");
                             field2.setText("");
                             field3.setText("");
    field4.setText("");
              JOptionPane.showMessageDialog(null,"Record modified");
    //buttonUpdate.setEnabled(true);
    //buttonModifyRecord.setEnabled(false);
                        }// end try
                        catch (SQLException ex)
                             System.out.println("SQLException:" + ex.getMessage() + "<BR>");
                        }// catch
    }// action performed
    } // anonymous inner class
    );// end addActionListener
    //---------Method to modify record------------------------------------
    buttonDelete.addActionListener(
    //anonymous class
    new ActionListener()
                   public void actionPerformed(ActionEvent event)
                        //Connection sqlca = null;
                   Statement sqlStatement = null;
                   ResultSet rset = null;
                   try{
                             //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                             //sqlca= DriverManager.getConnection ("jdbc:oracle:thin:@dbserver:1521:infs", "manzur", "manzur");
                             sqlStatement = sqlconn.createStatement ();
    int CUSTOMERID = Integer.parseInt(field1.getText());
              //String d_name = field2.getText();
                             //String d_loc = field3.getText();
                             String deletequery = "DELETE from CUSTOMERS "
    + " Where CUSTOMER_ID = " + CUSTOMERID;
              // execute the query
                             sqlStatement.executeQuery(deletequery);
                             // clear the textfields
                             field1.setText("");
                             field2.setText("");
                             field3.setText("");
    field4.setText("");
              JOptionPane.showMessageDialog(null,"Record Deleted");
    //buttonUpdate.setEnabled(true);
    //buttonModifyRecord.setEnabled(false);
                        }// end try
                        catch (SQLException ex)
                             System.out.println("SQLException:" + ex.getMessage() + "<BR>");
                        }// catch
    }// action performed
    } // anonymous inner class
    );// end addActionListener
    // specify the size of the window
    setSize(800,500);
    show();
    }// constructor
    public static void main(String args[]) throws IOException{
    OracleJavaCustomerWindow application = new OracleJavaCustomerWindow();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }// main
    } // class OracleJavaWindow
    // exceptions classes
    // inserFailedException is a general exception for
    // SQL insert problems
    /*class insertFailedException extends SQLException
    public insertFailedException(String reason)
         super(reason);
    public insertFailedException(String reason)
         super();
    }*/

    Sorry guys here is the correction of details i have provided
    the Error message tells me that
    package oracle.jdbc.driver does not exist
    and the folder I used to do Mounting SystemFile for was
    C:\Oracle\jdbc\lib\classes12

  • Workaround for using Oracle JDBC extension with WLS pooling

    Reading the newsgroup I saw that many of us encountered the problems
    with ClassCastException when tried to use Oracle JDBC extension
    with WLS pooling. I also had.
    In this case BEA recommends to use dangerous
    method getVendorConnection() which exposes
    the physical connection object to your code.
    Yes it's really dangerous because of unsafe usage may breaks
    WLS pooled connection(s).
    Moreover, this practice will make your JDBC code
    unportable (your JDBC code in addition to Oracle dependence
    became Weblogic dependent):
    void doSmth() {
    Connection con = ...;
    Connection vCon = ((WLConnection)con).getVendorConnection();
    // + mess of usage con in one places and vCon in others
    // (where Oracle extensions are needed)
    // !Don't forget to don't close vCon!
    Sux.
    I found the workaround.
    Introduction
    ============
    Yes the real cause of ClassCastException is that
    in depth of Oracle driver the casting
    to class oracle.jdbc.driver.OracleConnection
    (not to interface oracle.jdbc.OracleConnection)
    is performed.
    Someone can say that this is bug or pure desing.
    Weblogic pooled connection provide dynamic
    implementation for all public interfaces
    which real physical (wrapped) connection object implements.
    Great feature!
    But I guess that all interface methods implemented
    by simple call-delegation to physical (wrapped) connection object.
    In case of oracle.jdbc.OracleConnection interface
    this approach doesn't work for at least one its method:
    public OracleConnection unwrap()
    WLS pooled connection shoudn't implement this method by
    delegation to physical connection object BUT should
    return physical connection object itself!
    // Wrong implementation of unwrap()
    // delegation is used
    public OracleConnection unwrap() {
    return physicalConnection.unwrap();
    // Right implementation of unwrap()
    // physical connection returned
    public OracleConnection unwrap() {
    return physicalConnection;
    Workaround
    ==========
    1. Develop your own OracleConnection wrapper class:
    import oracle.jdbc.OracleConnection;
    import weblogic.jdbc.extensions.WLConnection;
    public class MyOracleConnectionImpl implements OracleConnection {
    private OracleConnection con;
    public MyOracleConnectionImpl(OracleConnection connection)
    throws SQLException
    this.con = connection;
    public OracleConnection unwrap() {
    return (OracleConnection)
    ((WLConnection)con).getVendorConnection();
    /* Implement all other methods by delegation to con object */
    2. Don't get Connections directly from DataSource --
    develop your own simple (may be static) utility
    class which retrives Connections from dataSource
    and returns them wrapped into your MyOracleConnectionImpl
    to your code from some method:
    puclic abstract class MyConnectionSource {
    public static Connection getConnection() {
    Connection con = // get it from DataSource
    return new MyOracleConnectionImpl((OracleConnection)con);
    3. Add attribute RemoveInfectedConnectionsEnabled="false"
    to definition of your JDBCConnectionPool within config.xml
    You may do it because of you `safely` use vendorConnection --
    you don't expose it to application code.
    4. Enjoy the Oracle JDBC extensions in your code!
    Example:
    Connection con = MyConnectionSource.getConnection;
    ArrayDescriptor add =
    ArrayDescriptor.createDescriptor("your_type", con);
    Hope it helps to someone.
    Best regards,
    Eugene Voytitsky

    Hello Eugene Voytitsky,
    Thanks Eugene Voytitsky for your idea
    I have tried the solution suggested by You, but it did not work.
    It still throws ClassCastException.
    I am sorry for posting the whole code of two classes below.
    I did this to give you more clarity.
    I am also indicating the place where the exception was thrown..
    Please let me know if I am doing something wrong.
    OracleConnection Wrapper class
    package ejbTesting;
    // sql imports
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.sql.SQLWarning;
    import java.sql.Statement;
    // util imports
    import java.util.Map;
    import java.util.Properties;
    // imports from Oracle Driver Classes
    import oracle.jdbc.OracleConnection;
    import oracle.jdbc.OracleOCIFailover;
    import oracle.jdbc.OracleSavepoint;
    // import from Weblogic extensions
    import weblogic.jdbc.extensions.WLConnection;
    public class WeblogicConnectionWrapper implements OracleConnection
         // oracle connection object
         private OracleConnection connection;
         public WeblogicConnectionWrapper (OracleConnection orclConnection)
              try
                   this.connection = orclConnection;
              catch(Exception unexpected )
                   unexpected.printStackTrace();
         public OracleConnection unwrap()
              try
              // The datasource returns a weblogic.jdbc.pool.Connection
              // This needs to be type casted to weblogic.jdbc.extensions.WLConnection
              // Only this weblogic.jdbc.extensions.WLConnection CAN BE type casted
              // to OracleConnection
         return (OracleConnection) ((WLConnection) connection).getVendorConnection();
         catch(Exception sqlException )
              sqlException.printStackTrace ();
              return null;
         /* Implement all other methods by delegation to connection object */      
    public Connection _getPC()
    return connection._getPC();
    public void archive(int i, int j, String s)
    throws SQLException
    connection.archive(i, j, s);
    public void assertComplete()
    throws SQLException
    connection.assertComplete();
    public void clearWarnings()
    throws SQLException
    connection.clearWarnings();
    public void close()
    throws SQLException
    connection.close();
    public void commit()
    throws SQLException
    connection.commit();
    public Statement createStatement()
    throws SQLException
    return connection.createStatement();
    public Statement createStatement(int i, int j)
    throws SQLException
    return connection.createStatement(i, j);
    public boolean getAutoClose()
    throws SQLException
    return connection.getAutoClose();
    public boolean getAutoCommit()
    throws SQLException
    return connection.getAutoCommit();
    public CallableStatement getCallWithKey(String s)
    throws SQLException
    return connection.getCallWithKey(s);
    public String getCatalog()
    throws SQLException
    return connection.getCatalog();
    public boolean getCreateStatementAsRefCursor()
    return connection.getCreateStatementAsRefCursor();
    public int getDefaultExecuteBatch()
    return connection.getDefaultExecuteBatch();
    public int getDefaultRowPrefetch()
    return connection.getDefaultRowPrefetch();
    public Object getDescriptor(String s)
    return connection.getDescriptor(s);
    public boolean getExplicitCachingEnabled()
    throws SQLException
    return connection.getExplicitCachingEnabled();
    public boolean getImplicitCachingEnabled()
    throws SQLException
    return connection.getImplicitCachingEnabled();
    public boolean getIncludeSynonyms()
    return connection.getIncludeSynonyms();
    public Object getJavaObject(String s)
    throws SQLException
    return connection.getJavaObject(s);
    public DatabaseMetaData getMetaData()
    throws SQLException
    return connection.getMetaData();
    public Properties getProperties()
    return connection.getProperties();
    public boolean getRemarksReporting()
    return connection.getRemarksReporting();
    public boolean getRestrictGetTables()
    return connection.getRestrictGetTables();
    public String getSQLType(Object obj)
    throws SQLException
    return connection.getSQLType(obj);
    public String getSessionTimeZone()
    return connection.getSessionTimeZone();
    public int getStatementCacheSize()
    throws SQLException
    return connection.getStatementCacheSize();
    public PreparedStatement getStatementWithKey(String s)
    throws SQLException
    return connection.getStatementWithKey(s);
    public int getStmtCacheSize()
    return connection.getStmtCacheSize();
    public short getStructAttrCsId()
    throws SQLException
    return connection.getStructAttrCsId();
    public boolean getSynchronousMode()
    return connection.getSynchronousMode();
    public int getTransactionIsolation()
    throws SQLException
    return connection.getTransactionIsolation();
    public Map getTypeMap()
    throws SQLException
    return connection.getTypeMap();
    public String getUserName()
    throws SQLException
    return connection.getUserName();
    public boolean getUsingXAFlag()
    return connection.getUsingXAFlag();
    public SQLWarning getWarnings()
    throws SQLException
    return connection.getWarnings();
    public boolean getXAErrorFlag()
    return connection.getXAErrorFlag();
    public boolean isClosed()
    throws SQLException
    return connection.isClosed();
    public boolean isLogicalConnection()
    return connection.isLogicalConnection();
    public boolean isReadOnly()
    throws SQLException
    return connection.isReadOnly();
    public String nativeSQL(String s)
    throws SQLException
    return connection.nativeSQL(s);
    public Object openJoltConnection(String s, short word0, short word1)
    return connection.openJoltConnection(s, word0, word1);
    public void oracleReleaseSavepoint(OracleSavepoint oraclesavepoint)
    throws SQLException
    connection.oracleReleaseSavepoint(oraclesavepoint);
    public void oracleRollback(OracleSavepoint oraclesavepoint)
    throws SQLException
    connection.oracleRollback(oraclesavepoint);
    public OracleSavepoint oracleSetSavepoint()
    throws SQLException
    return connection.oracleSetSavepoint();
    public OracleSavepoint oracleSetSavepoint(String s)
    throws SQLException
    return connection.oracleSetSavepoint(s);
    public int pingDatabase(int i)
    throws SQLException
    return connection.pingDatabase(i);
    public CallableStatement prepareCall(String s)
    throws SQLException
    return connection.prepareCall(s);
    public CallableStatement prepareCall(String s, int i, int j)
    throws SQLException
    return connection.prepareCall(s, i, j);
    public CallableStatement prepareCallWithKey(String s)
    throws SQLException
    return connection.prepareCallWithKey(s);
    public PreparedStatement prepareStatement(String s)
    throws SQLException
    return connection.prepareStatement(s);
    public PreparedStatement prepareStatement(String s, int i, int j)
    throws SQLException
    return connection.prepareStatement(s, i, j);
    public PreparedStatement prepareStatementWithKey(String s)
    throws SQLException
    return connection.prepareStatementWithKey(s);
    public void purgeExplicitCache()
    throws SQLException
    connection.purgeExplicitCache();
    public void purgeImplicitCache()
    throws SQLException
    connection.purgeImplicitCache();
    public void putDescriptor(String s, Object obj)
    throws SQLException
    connection.putDescriptor(s, obj);
    public void registerApiDescription(String s, short word0, short word1, String
    s1)
    connection.registerApiDescription(s, word0, word1, s1);
    public void registerSQLType(String s, Class class1)
    throws SQLException
    connection.registerSQLType(s, class1);
    public void registerSQLType(String s, String s1)
    throws SQLException
    connection.registerSQLType(s, s1);
    public void registerTAFCallback(OracleOCIFailover oracleocifailover, Object
    obj)
    throws SQLException
    connection.registerTAFCallback(oracleocifailover, obj);
    public void rollback()
    throws SQLException
    connection.rollback();
    public void setAutoClose(boolean flag)
    throws SQLException
    connection.setAutoClose(flag);
    public void setAutoCommit(boolean flag)
    throws SQLException
    connection.setAutoCommit(flag);
    public void setCatalog(String s)
    throws SQLException
    connection.setCatalog(s);
    public void setCreateStatementAsRefCursor(boolean flag)
    connection.setCreateStatementAsRefCursor(flag);
    public void setDefaultExecuteBatch(int i)
    throws SQLException
    connection.setDefaultExecuteBatch(i);
    public void setDefaultRowPrefetch(int i)
    throws SQLException
    connection.setDefaultRowPrefetch(i);
    public void setExplicitCachingEnabled(boolean flag)
    throws SQLException
    connection.setExplicitCachingEnabled(flag);
    public void setImplicitCachingEnabled(boolean flag)
    throws SQLException
    connection.setImplicitCachingEnabled(flag);
    public void setIncludeSynonyms(boolean flag)
    connection.setIncludeSynonyms(flag);
    public void setReadOnly(boolean flag)
    throws SQLException
    connection.setReadOnly(flag);
    public void setRemarksReporting(boolean flag)
    connection.setRemarksReporting(flag);
    public void setRestrictGetTables(boolean flag)
    connection.setRestrictGetTables(flag);
    public void setSessionTimeZone(String s)
    throws SQLException
    connection.setSessionTimeZone(s);
    public void setStatementCacheSize(int i)
    throws SQLException
    connection.setStatementCacheSize(i);
    public void setStmtCacheSize(int i)
    throws SQLException
    connection.setStmtCacheSize(i);
    public void setStmtCacheSize(int i, boolean flag)
    throws SQLException
    connection.setStmtCacheSize(i, flag);
    public void setSynchronousMode(boolean flag)
    connection.setSynchronousMode(flag);
    public void setTransactionIsolation(int i)
    throws SQLException
    connection.setTransactionIsolation(i);
    public void setTypeMap(Map map)
    throws SQLException
    connection.setTypeMap(map);
    public void setUsingXAFlag(boolean flag)
    connection.setUsingXAFlag(flag);
    public void setWrapper(OracleConnection oracleconnection)
    connection.setWrapper(oracleconnection);
    public void setXAErrorFlag(boolean flag)
    connection.setXAErrorFlag(flag);
    public void shutdown(int i)
    throws SQLException
    connection.shutdown(i);
    public void startup(String s, int i)
    throws SQLException
    connection.startup(s, i);
    Util class to get Wrapped Connections from
    datasource
    package ejbTesting;
    // j2ee imports
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    // sql imports
    import java.sql.Connection;
    // imports from Oracle Driver Classes
    import oracle.jdbc.OracleConnection;
    * Wrapper class for the DataSource Connection from Weblogic pool
    public class DataSourceConnectionWrapper
         // datasource variable
         private static transient DataSource datasource = null;
         private static String dbName = "jdbc/workbench";
    * Method that returns the database connection
         public static Connection getConnection()
              try
                   // initialsing the datasource object
                   initialiseDataSource ();
                   // Getting a connection from the datasource
                   Connection con = datasource.getConnection( );
                   // wrapping it custom wrapper class and
                   // returning the connection object
                   return new WeblogicConnectionWrapper((OracleConnection)con);
              catch(Exception exception )
                   exception.printStackTrace();
                   return null;
         private static void initialiseDataSource( ) throws Exception
    if ( datasource == null )
    try
    InitialContext ic = new InitialContext( );
    datasource = (DataSource) ic.lookup( dbName );
    catch (Exception ne )
    throw new Exception( "NamingException while looking up DataSource with
    JNDI name" +
    dbName + ": \n" + ne.getMessage( ) );
    Exception Stack Trace
    The line 46 in DataSourceConnectionWrapper
    corresponds to
    return new WeblogicConnectionWrapper((OracleConnection)con);
    Which I feel is logical as the connection which we get from Weblogic
    datasource cannot be type casted to OracleConnection
    java.lang.ClassCastException: weblogic.jdbc.pool.Connection
    at ejbTesting.DataSourceConnectionWrapper.getConnection(DataSourceConnectionWrapper.java:46)

  • JSP and DB2 Connection

    I tried to use this class in my jsp page to connect to the DB2 database, However, no data from the DB appears on the page and i get no errors whatsoever. Can anyone be kind enough to take a look? Thanks
    package WH;
    import java.sql.*;
    import java.sql.Statement;
    public class DbConnect1 {
    private String dbUser = "XXX";
    private String dbPasswd = "XXX";
    private String dbDriver = "COM.ibm.db2.jdbc.app.DB2Driver";
    private String dbURL = "jdbc:db2:http://xx.xx.xxx.xx:8080/invsys";
    private Connection dbCon;
    public DbConnect1(){}
    public boolean connect() throws ClassNotFoundException,SQLException{
    try
    Class.forName(dbDriver);
    System.out.println("Loaded the instantDB JDBC driver.");
    dbCon = DriverManager.getConnection(dbURL, dbUser, dbPasswd);
    System.out.println("Created and connected to database TimingTest");
    return true;
    catch (Throwable e)
    e.printStackTrace();
    System.out.println("FAIL LAHHHHHHHHHHHH");
    return false;
    public void close() throws SQLException{
    dbCon.close();
    //accepts the SQL query in the form of a string from the JSP file in which this bean is implemented
    public ResultSet execSQL(String sql) throws SQLException{
    System.out.println("haha");
    //initiates the connection with the dbCon connection object
    Statement s = dbCon.createStatement();
    ResultSet r = s.executeQuery(sql);
    return (r == null) ? null : r;
    public int updateSQL(String sql) throws SQLException{
    Statement s = dbCon.createStatement();
    int r = s.executeUpdate(sql);
    return (r == 0) ? 0 : r;

    Here is a copy of my JSP file.
    <%@ page language='java' %>
    <%@ page import="java.sql.*" %>
    <jsp:useBean id="DbConnectBean1" scope="page" class="WH.DbConnect1" />
    <%
         //Get status
         /*String message;
         String status = request.getParameter("status").trim();
         if (status == "duplicateEmail")
         message="Please try again. An account with the same emaill address has already been created.";
         else if (status == "deleteOk")
         message="Delete successful.";
         else
              message="";*/
    //Get Contacts
         String name;
         String email;
         String extNo;
         String phoneNo;
         String remarks;
         String SQLstmt;
         SQLstmt = "Select * from CONTACT";
    if (DbConnectBean1.connect()==true){
    %>
    <html>
    <head>
    <title>Display Contacts</title>
    <script src="validation.js" language="Javascript"></script>
    <script Language="JavaScript">
    //Perform Validation
    /* function checkForm() {
    var alertString=checkChkBox(theForm.chkItem.value);
         formSubmit(alertString);
    </script>
    </head>
    <body bgcolor="#ffffff">
    <form action="USRDelContact.jsp" name="theForm" onsubmit="return checkForm();">
    </form>
    <table>
    <tr>
    <td><input type="chkAll" id="chkAll"onclick="checkAll(document.theForm.chkItem)"/></td>
    <td>Name</td>
    <td>Extension No.</td>
    <td>Mobile Phone No.</td>
    <td>Email Address</td>
    <td>Remarks</td>
    <td> </td>
    </tr>
    <%
         ResultSet r = DbConnectBean1.execSQL(SQLstmt);
         while (r.next()){
    %>
    <tr>
    <td><input type="checkbox" name="chkItem" id="chkItem" value="<%= r.getString("Email")%>"/></td>
    <td><%= r.getString("Emp_Name")%></td>
    <td><%= r.getString("Ext_No")%></td>
    <td><%= r.getString("Cellphone")%></td>
    <td><a href="mailto:<%= r.getString(Email")%">"><%= r.getString("Email")%></a></td>
    <td><%= r.getString("Remarks")%></td>
    <td><a href="USREditContact.jsp?email=<%= r.getString("Email")%>">Edit</a></td>
    </tr>
    <%
    if (r.next()==false)
    %>
    <tr>
    <td colspan="7">There are no records currently.</td>
    </tr>
    <% }
    }//end if%>
    <tr colspan="6">
    <td>
    <%//=message%> <input type="submit" name="btnDelete" value="Delete">
    </td>
    </tr>
    </table>
    </form>
    </body>
    </html>
    </a>

  • Connection Pooling doesn't work.

    Good day. all
    I've tested OracleConnectionPoolDataSource and OracleDataSource.
    And found that there is no performance difference. And connections are not pooled to my mind.
    My sample fill table with records, and than read and update concurrently it in two threads.
    Bellow is a code provided.
    <strong>
    A piece of logs</strong>: each time new connection is created.
    connection= oracle.jdbc.driver.OracleConnection@1198891
    0. updatedNumber= 1
    connection.close()= oracle.jdbc.driver.OracleConnection@1198891
    connection= oracle.jdbc.driver.OracleConnection@17725c4
    connection.close()= oracle.jdbc.driver.OracleConnection@17725c4
    list.size()= 10
    0, name_update0, name_desc0, name_status0, 2008-11-04, 2008-11-04.
    1, a1, c1, b1, 2008-11-04, 2008-11-04.
    viewing the logs I see that every time new connection is created in both cases whether I use OracleConnectionPoolDataSource or OracleDataSource.
    <strong>
    Question:</strong> Can anybody help me to understand how to use Connnection pooling? And how to see with my own eyes that it works?
    <strong>DDL</strong>:
    to run the program one should create table:
    {color:#000080}CREATE TABLE TEST_RECORD1 (
    ID NUMBER(10) NOT NULL PRIMARY KEY,
    NAME VARCHAR2(255 BYTE) ,
    STATUS VARCHAR2(255 BYTE) ,
    DESCRIPTION VARCHAR2(255 BYTE),
    START_DATE TIMESTAMP ,
    END_DATE TIMESTAMP
    );{color}
    <strong>
    Java Code</strong>:
    package test.jdbc;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import javax.sql.ConnectionPoolDataSource;
    import javax.sql.DataSource;
    import oracle.jdbc.pool.OracleConnectionPoolDataSource;
    import oracle.jdbc.pool.OracleDataSource;
    public class TestConnectionPooling2 {
    static DataSource dataSource;
    /** number of iterations */
    static final long BASE_REPEAT_NUMBER = 5;
    static final long RECORDS_NUMBER = 10;
    public static void main(String[] args) throws Exception {
    //here you can change data source (pooled or no), but performance won''t change
    // setupDataSource( new OracleDataSource());
    setupDataSource(new OracleConnectionPoolDataSource());
    long startTime = System.currentTimeMillis();
    //clean table
    removeAllRecords("delete from test_record1");
    //insert records into table
    for (int i = 0; i &lt; RECORDS_NUMBER; i++) {
    insertRecord(i,
    "insert into TEST_RECORD1 (id,name,status, description, start_date, end_date) "
    + " values (?, ?, ?, ?, ?, ?)");
    //setup thread which queries data from table
    Thread th1 = new Thread("thread 1") {
    public void run() {
    for (int i = 0; i &lt; BASE_REPEAT_NUMBER; i++) {
    retrieveRecords("select * from test_record1 order by id asc");
    Thread.yield();
    //setup thread which updates data on table
    Thread th2 = new Thread("thread 2") {
    public void run() {
    for (int counter = 0; counter &lt; BASE_REPEAT_NUMBER; counter++) {
    for (int i = 0; i &lt; RECORDS_NUMBER; i++) {
    performSingleUpdate(counter, i,
    "update TEST_RECORD1 set name = ?, description=?, status=? where id=?");
    Thread.yield();
    th1.start();
    th2.start();
    //do not finish until threads work
    while (th1.isAlive() || th2.isAlive()) {
    Thread.yield();
    long endTime = System.currentTimeMillis();
    System.out.println("Execution time:" + (endTime - startTime) + " ms.");
    private static void performSingleUpdate(long counter, long i, String sql) {
    PreparedStatement stmt = null;
    Connection conn2 = getConnection();
    try {
    stmt = conn2.prepareStatement(sql);
    long temp = counter * 10 + i;
    stmt.setString(1, "name_update" + temp);
    stmt.setString(2, "name_desc" + temp);
    stmt.setString(3, "name_status" + temp);
    stmt.setLong(4, i);
    int updatedNumber = stmt.executeUpdate();
    System.out.println(counter + ". updatedNumber= " + updatedNumber);
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    try {
    stmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    if (conn2 != null) {
    closeConnection(conn2);
    private static void removeAllRecords(String deleteAllSQL) {
    Statement stmt = null;
    Connection conn2 = getConnection();
    try {
    stmt = conn2.createStatement();
    int updatedNumber = stmt.executeUpdate(deleteAllSQL);
    System.out.println("Deleting all records. updatedNumber= " + updatedNumber);
    stmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    if (conn2 != null) {
    closeConnection(conn2);
    public static void retrieveRecords(String sql) {
    List list = new ArrayList();
    Statement stmt = null;
    ResultSet resultset = null;
    int recordsCounter = 0;
    Connection connection = getConnection();
    try {
    stmt = connection.createStatement();
    resultset = stmt.executeQuery(sql);
    while (resultset.next()) {
    Record newRecord = new Record();
    recordsCounter++;
    newRecord.setId(resultset.getLong("id"));
    newRecord.setName(resultset.getString("name"));
    newRecord.setDesc(resultset.getString("description"));
    newRecord.setStatus(resultset.getString("status"));
    newRecord.setStartDate(resultset.getDate("start_Date"));
    newRecord.setEndDate(resultset.getDate("end_Date"));
    list.add(newRecord);
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    if (resultset != null)
    try {
    resultset.close();
    } catch (Exception e) {
    e.printStackTrace();
    if (stmt != null)
    try {
    stmt.close();
    } catch (Exception e) {
    e.printStackTrace();
    if (connection != null) {
    closeConnection(connection);
    StringBuilder sb2 = new StringBuilder("list.size()= " + list.size() + "\n");
    for (int i = 0; i &lt; list.size(); i++) {
    Record record = (Record)list.get(i);
    sb2.append(" " + record.toString() + "\n");
    System.out.println("" + sb2);
    public static void insertRecord(long counter, String sql) {
    PreparedStatement stmt = null;
    Connection conn2 = getConnection();
    try {
    stmt = conn2.prepareStatement(sql);
    stmt.setLong(1, counter);
    stmt.setString(2, "a" + counter);
    stmt.setString(3, "b" + counter);
    stmt.setString(4, "c" + counter);
    stmt.setTimestamp(5, new java.sql.Timestamp(System.currentTimeMillis()));
    stmt.setTimestamp(6, new java.sql.Timestamp(System.currentTimeMillis()));
    int updatedNumber = stmt.executeUpdate();
    System.out.println(counter + ".insertNumber= " + updatedNumber);
    } catch (SQLException e) {
    e.printStackTrace();
    } finally {
    try {
    stmt.close();
    } catch (SQLException e) {
    e.printStackTrace();
    if (conn2 != null) {
    closeConnection(conn2);
    // Initial methods
    private static void setupDataSource(OracleDataSource oracleDataSource) throws SQLException {
    OracleDataSource ds = oracleDataSource;
    ds.setUser("akhlystov");
    ds.setPassword("xallex");
    ds.setURL("jdbc:oracle:thin:@localhost:1521:abc");
    dataSource = ds;
    public static DataSource getDataSource() {
    return dataSource;
    private static void closeConnection(Connection connection) {
    if (conn != null) {
    return;
    System.out.println("connection.close()= " + connection + "\n");
    try {
    connection.close();
    } catch (SQLException e) {
    throw new RuntimeException(
    "application should not work when database can't close connection");
    static Connection conn;
    public static Connection getConnection() {
    * uncomment to test without any data source, single connection if ( conn ==
    * null){ try { conn = getDataSource().getConnection(); } catch
    * (SQLException e) { e.printStackTrace(); } } return conn;
    try {
    Connection connection =null;
    if ( getDataSource() instanceof ConnectionPoolDataSource){
    connection = ((ConnectionPoolDataSource)getDataSource()).getPooledConnection().getConnection();
    }else{
    connection = getDataSource().getConnection();
    System.out.println("connection= " + connection);
    return connection;
    } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("application should not work when database is unavailable");
    // Record class
    static class Record {
    long id;
    String name;
    String desc;
    String status;
    Date startDate;
    Date endDate;
    public long getId() {
    return id;
    public void setId(long id) {
    this.id = id;
    public String getName() {
    return name;
    public void setName(String name) {
    this.name = name;
    public String getDesc() {
    return desc;
    public void setDesc(String desc) {
    this.desc = desc;
    public String getStatus() {
    return status;
    public void setStatus(String status) {
    this.status = status;
    public Date getStartDate() {
    return startDate;
    public void setStartDate(Date startDate) {
    this.startDate = startDate;
    public Date getEndDate() {
    return endDate;
    public void setEndDate(Date endDate) {
    this.endDate = endDate;
    public String toString() {
    return id + ", " + name + ", " + desc + ", " + status + ", " + startDate + ", " + endDate + ".";
    Edited by: Alexandr Khlystov on 04.11.2008 20:14

    The relevant documentation for the 9i JDBC drivers is here http://download.oracle.com/docs/cd/B10501_01/java.920/a96654/connpoca.htm#1056354.
    In the 9i JDBC driver world,there was a distinction between a connection pool (pooled connection) and a connection cache.
    A connection pool attempts to eliminate the overhead and resource consumption of connecting and disconnecting from the database. If the connection is going to be reused then no point in closing the connection just to open it up again.
    What performance gain were you looking for? You would only see a performance gain if your application was constantly opening and closing connections, requiring all the resources to setup and tear down database communications. Once a connection is established there is no difference in performance of the execution of SQL.
    You can see this with
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import oracle.jdbc.pool.OracleConnectionPoolDataSource;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.jdbc.pool.OraclePooledConnection;
    public class TestConnectionCache {
      public static void exec(Connection conn) throws SQLException {
        ResultSet rs = conn.prepareStatement("select sys_context('USERENV','SESSIONID') from dual").executeQuery();
        rs.next();
        System.out.println("Session id: " + rs.getInt(1));
        conn.close();
      public static void main(String[] args) throws SQLException {
        OracleDataSource ods = new OracleConnectionPoolDataSource();
        ods.setUser("...");
        ods.setPassword("...");
        // Construct the jdbc url.
        String host     = "...";
        String port     = "...";
        String instance = "...";
        String url =
          "jdbc:oracle:thin:@//" + host + ":" + port + "/" + instance
        ods.setURL(url);
        // No connection re-use.
        exec(ods.getConnection());
        exec(ods.getConnection());
        // Connection re-use. (Connection pooling)
        OraclePooledConnection opc = (OraclePooledConnection)((OracleConnectionPoolDataSource)ods).getPooledConnection();
        exec(opc.getConnection());
        exec(opc.getConnection());
    }Produces output similar to:
    Session id: 4110149
    Session id: 4110150
    Session id: 4110151
    Session id: 4110151Note when connection pooliing is used, the database session id is the same. Calling close() did not close the physical connection.
    A connection cache is a layer on top of pooled connections that manages the creation and destruction of connections. It usually has limits as to how many connection it should open and the max number of connections to allow. Then when the cache is asked for a connection, it can return one that is not in use, or possibly create a new one.
    The later versions of the JDBC driver greatly simplify managing your connections and here is the note from the docs:
    Note:
    The previous cache architecture, based on OracleConnectionCache and OracleConnectionCacheImpl, is deprecated. Oracle recommends that you take advantage of the new architecture, which is more powerful and offers better performance.
    Any reason why your are not using a more recent JDBC driver?

  • Weird JDBC

    import java.net.*;
    import java.io.*;
    import java.sql.*;
    class Update{
         public static void main(String[] args){
              try{
                   int iField = 1;          
                   InetAddress iAdd = InetAddress.getLocalHost();
                   String strDriver          = "sun.jdbc.odbc.JdbcOdbcDriver";
                   String strConnection     = "jdbc:odbc:RemoteOverride";
                   String strSQL                = " UPDATE PC_USERS SET " + "Active = " + "'" + iField + "'" + " Where PC_Name = " + "'" + iAdd.getHostName() + "'";
                   System.out.println(" My name is: " + iAdd.getHostName() );
                   System.out.println("The SQL stmt is " + strSQL);
                   //UPDATE PC_USERS SET Active = '1' Where PC_Name = 'C38TC010'
                   Class.forName(strDriver);
                   Connection conn      = DriverManager.getConnection(strConnection,"","" );
                   Statement stmt           = conn.createStatement();                         
                   int iUpdate = stmt.executeUpdate( strSQL );
                   System.out.println("update == " + iUpdate);     
              }catch(Exception e) { System.out.println("Error in InetAddress " + e);}
    this is my program....this program tries to update the 'Active' field of the PC_USERS table...when i try to run the query(the one at the comment field) at MS ACCESS, it is perfectly working but when i try to run the program nothing is happening...the executeUpdate method returns '1' so i guess that means there is no error or whatsoever....i thought maybe i've been editing another database so i tried to rename the DB and the program noticed that it is pointing to a non existing dbase so it threw an exception....so it means it is pointing to the database that im working on with this program.....hope you can help me guys!

    There are better - more performant ways.
    Look at this discussion of that stupid Access problem:
    http://forum.java.sun.com/thread.jsp?forum=48&thread=147704

Maybe you are looking for

  • Update Failure of OS 10.6 from OS 10.5.8

    I am using Mac Pro with OS 10.5.8, I recently bought a 10.6.3 disc and I can't install it to my computer. The 10.6 stop loading while it's still 45-49 mins left for installation, and switched to restart the computer. After that, it's still showing OS

  • Bridge or ACR problem?

    Hi, few days  ago I started to have a problem with either Bridge or ACR.  I open a raw file in ACR and save it as jpg  with no settings changed, when I open the jpg (through ACR) it would increase the contrast to +23, change the the shadows and curve

  • Chapter id description

    Hi, What are the different table from which we can details regarding Both chapter id & descritpion

  • Disabling comboboxes after a certain limit has been met

    I have 4 comboboxes called: cboOption1  cboOption2  cboOption3  cboOption4 Each of them can have one of 2 values, either 10 or 20 points, which the user selects from a drop down. However, the user can only select a maximum of 40 points across all dro

  • DBIO_EXPECTED

    Hi experts, Oracle says that the i/o performance analysis is affected by the dbio_expected parameter which should be set to the average time(in microseconds) it takes to read a single database block from the disk with typical values range from 5000 t