Can someone checkout this JDBC code for me?

I'd be very grateful if an expert out there would check out my code for me, which I am about to use a great deal.
I've written this to save me some duplicated code, but since I haven't seen this approach much in my travels, I'm wondering if it has any particular flaws.
A separate DbAccess class is instantiated for any database access work, and once instantiated, getConnection is called and once finished closeConnection must be called.
You can get a ResultSet instance with just a little code and it's up to the calling programme to close it again.
The only things left open are the Statements, but they will get garbage collected or at any rate will be closed with the connection (whichever is sooner).
Is there anything wrong with this code?
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
public class DbAccess{
     * The chosen datasource for this instance of the class
    private String dataSource;
     * The connection held in this instance (created by calling getConnection())
    private Connection con;
     * Instantiates a DbAccess instance, setting the datasource
    public DbAccess(String datasource){
     this.dataSource = dataSource;
     * Gets a connection to the database chosen in constructor parameter:
     * NB The calling programme MUST call closeConnection() after it's finished with it!
    public void getConnection()
     throws NamingException,
            SQLException{
     Context ctx = new InitialContext();
     DataSource ds = (DataSource)ctx.lookup(dataSource);
     con = ds.getConnection();
    }//end getConnection()
     * Closes the connection previously obtained with getConnection(), this MUST be called when the calling
     * programme has finished using the database.
    public void closeConnection()
     throws SQLException{
     con.close();
    }//end closeConnection()
     * Returns a ResultSet for a simple query, using a plain Statement
     * @param query - the complete database query
     * @return ResultSet for the query in the parameter
     * N.B. The calling programme MUST close the ResultSet after it's finished with it!
    public ResultSet getResultSet(String query)
     throws SQLException{
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(query);
     return rs;
    }//end getResultSet()
     * Returns a ResultSet for a simple query, using a PreparedStatement, and accepting
     * a String parameter that can contain a String for a single setString().
     * @param query - the complete database query
     * @param stringToSet - the String for the preparedStatement's setString() method
     * @return ResultSet for the query in the parameter
     * N.B. The calling programme MUST close the ResultSet after it's finished with it!
    public ResultSet getResultSet(String query, String stringToSet)
     throws SQLException{
     PreparedStatement ps = con.prepareStatement(query);
     ps.setString(1,stringToSet);
     ResultSet rs = ps.executeQuery();
     return rs;
    }//end getResultSet()
}//end class

Ok, guys you've thoroughly trashed my code, fine, and
I half expected it because there's nothing like this
code about the placeYou're suffering from delusions of grandeur. There are plenty of approaches to that particular itch. The closest to what you're trying to achieve would probably be Spring's JDBCTemplate:
http://www.springframework.org/docs/api/org/springframework/jdbc/core/JdbcTemplate.html
Hibernate, iBatis, EJB3, and myriad others tackle the issue in other ways.
, but are we therefore concluding
that reducing the jdbc code is virtually impossibile
- and there's an awful lot of it every time you want
to do a query?My major objection to your approach is that you introduce a variety of bugs without significantly reducing the amount of JDBC code required. Most of what you're after in your class can be achieved by a convenience method to acquire the Connection object.
1) If (ok maybe it's a big if) - if I always close
the connection, the statements aren't being leaked
right?Not necessarily. To the best of my recollection the spec doesn't mandate this. And even if it does I've certainly encountered drivers that don't clean up statement resources that aren't explicitly released. So there's a theoretical and practical aspect to this.
2) I'm using Tomcat datasources, for getting the
connection, and I thought that you just had to call
con.close() for it to return to the pool. Am I wrong
on this?No, you're right - but nothing in your class prevents the user from calling getConnection twice and leaking a connection - the least you could do in the circumstances is prevent that by throwing an exception if they try.

Similar Messages

  • Can someone perform this speaker test for me please

    Hi can someone perform this test for please, play some ipod music through your phone and and cover 1 speaker at a time with you finger, does 1 block out the music as if one speaker is much louder than the other ? just I have tried this on my new iphone 4 as thought it might be a problem but my 3GS is doing it to ??, is it fault or meant to be like that

    There's only one speaker.
    http://manuals.info.apple.com/enUS/iPhone_iOS4_UserGuide.pdf

  • Can someone decipher this crash report for me please? :(

    I have no clue why this is crashing.  Its just a simple TweenMAX that calls a function onStart and onComplete.
    I dont know what all these references are to apple.Music
    I see a lowMemory error as well ..  but my Profiler is showing that I'm hardly using any memory.  ??
    Apr 15 18:06:33 unknown kernel[0] <Debug>: launchd[2123] Builtin profile: container (sandbox)
    Apr 15 18:06:33 unknown kernel[0] <Debug>: launchd[2123] Container: /private/var/mobile/Applications/E88687CB-C4D3-4B7E-B61A-30AE1FF128A4 [69] (sandbox)
    >
    Apr 15 18:06:48 unknown com.apple.launchd[1] <Notice>: (UIKitApplication:com.apple.Music[0x3b9]) Exited: Killed: 9
    Apr 15 18:06:48 unknown com.apple.launchd[1] <Notice>: (UIKitApplication:com.apple.mobilemail[0xf1b8]) Exited: Killed: 9
    Apr 15 18:06:48 unknown SpringBoard[23] <Warning>: Application 'Music' exited abnormally with signal 9: Killed: 9
    Apr 15 18:06:48 unknown SpringBoard[23] <Warning>: Application 'Mail' exited abnormally with signal 9: Killed: 9
    Apr 15 18:06:48 unknown com.apple.launchd[1] <Notice>: (UIKitApplication:com.apple.mobilephone[0xaeff]) Exited: Killed: 9
    Apr 15 18:06:48 unknown SpringBoard[23] <Warning>: Application 'FaceTime' exited abnormally with signal 9: Killed: 9
    Apr 15 18:06:48 unknown UserEventAgent[12] <Notice>: jetsam: kernel termination snapshot being created
    Apr 15 18:06:48 unknown com.apple.launchd[1] <Notice>: (UIKitApplication:historyapp[0x2680]) Exited: Killed: 9
    Apr 15 18:06:48 unknown ReportCrash[2126] <Notice>: Saved crashreport to /Library/Logs/CrashReporter/LowMemory-2012-04-15-180648.plist using uid: 0 gid: 0, synthetic_euid: 0 egid: 0
    Apr 15 18:06:48 unknown SpringBoard[23] <Warning>: Application exited abnormally with signal 9: Killed: 9
    Apr 15 18:06:48 unknown kernel[0] <Debug>: launchd[2124] Builtin profile: MobileMail (sandbox)

    There's only one speaker.
    http://manuals.info.apple.com/enUS/iPhone_iOS4_UserGuide.pdf

  • Can Someone Confirm this Nano Action for me?

    I need to have an AIFF recording UNCOMPRESSED on my Nano.
    If I bring into iTunes as AIFF, will the Nano compress it when I download to the Nano?
    If so, can I use the Nano as a hard-drive and copy the AIFF file to it that way?
    Any help greatly appreciated.
    Thanks

    Yes, it will download uncompressed. It will take a lot more space but it will still sync to the nano as uncompressed. Syncing to your iPod will not compress your files unless you change the format yourself. The same format you imported the file to iTunes will be the same format sent to your nano.

  • I am updating iphoto 9.1 to 9.3 and every time when I clicked for update aps store asked to open it in the account where you purchased. I am using the same account and its available in the purchased item of this account. Can someone resolve this problem.

    I am updating iphoto 9.1 to 9.3 and every time when I clicked for update aps store asked to open it in the account where you purchased. I am using the same account and its available in the purchased item of this account. But in my purchased item library it indicates that you update iPhoto. I am not sure which account the aps store asking. Can someone resolve this problem.

    Contact App Store support. They're the folks who can help with Account issues.
    Regards
    TD

  • Hi can someone keep this simple for me! my iPhone is due for a renewal. but my old laptop that it is backed up to no longer works! how do i go about saving all my songs pics etc to a new laptop without losing anything? please help!!!

    hi can someone keep this simple for me! my iPhone is due for a renewal. but my old laptop that it is backed up to no longer works! how do i go about saving all my songs pics etc to a new laptop without losing anything? please help!!!

                     Syncing to a "New" Computer or replacing a "crashed" Hard Drive

  • Can anybody give me the jdbc code for postgres database.

    Hello all,
    I tried to search for sample jdbc code for postgres. But I couldn't find working sample. Can anybody please post the sample jdbc code for connecting to postgres database.
    I have already added the jar file, "postgresql-8.0-312.jdbc3.jar" to the build path.
    Thanks.
    Srinivas

    Hi,
    Thanks for your reply!
    I wrote the following code, but the insert doesn't add a row.
    try {
              Class.forName("org.postgresql.Driver");
              //Preparing Conenction String     
              Connection con = DriverManager.getConnection("jdbc:postgresql://<name>:5432/sales_office_test", "sales_office_data","sales_office_data");
              PreparedStatement prepSt =  con.prepareStatement(
                                  "INSERT INTO office_personnel (office_id, salutation, firstname, lastname, email_address,"
                                  + " cellphone, phonenumber, extension, password, username) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                             prepSt.setString(1, newOfficeIds);
                             prepSt.setString(2, whopperUserSalutation);
                             //Close statement
                             prepSt.close();
         } catch (ClassNotFoundException e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
         } catch (SQLException e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
         }If I print the connection object I get
    Sql connection value: org.postgresql.jdbc3.Jdbc3Connection@10965c3 I double checked the same query by directly executing it on the web interface to the postgres, works fine there and creates the row...
    What could be wrong.
    Thanks
    Srinivas

  • How can I get a verification code for Photoshop Elements 7 ?

    I CAN NOT GET A VERIFICATION CODE FOR PHOTOSHOP ELEMENTS 7
    SO I CAN SEND EMAIL WITH PHOTO.  WOULD SOMEONE TELL ME HOW
    TO GET THE VERIFICATION CODE. I HAVE TRIED REPEATABLY TO
    ADOBE WITH NO RESPONSE.
    CHARLES TODD
    Email:   [email protected]

    I am talking about that when I try to share a Photo from the Organizer of Photoshop Elements 7
    thru the use of Email attachment, It will not transmit.  I get a message that tells me to enter
    a "Verification Code".  I do not have a verification code and have been unable to get one from adobe.
    This is Photoshop Elements 7 which I bought from Adobe. It was a packet of Photoshop Elements 7
    and Photoshop Premiere Elements 7. Any advice would be appreciate.
    Charles Todd....Email:   [email protected]

  • Can someone execute this program?

    Can someone execute this program for me and tell me if it works correctly? My DOS is acting funny.
    look for these things:
    - accepts input from keyboard and places them into an array
    - continues to accept names until a blank name is entered
    - array can contain up to 15 names
    - after all names are entered, it displays the contents of the array
    and writes them to a file
    - output should be in 2 columns
    if you see a problem, please tell me how to fix it.
    import java.io.*;
    * the purpose of this program is to read data from the keyboard
    * and put it into a sequential file for processing by ReadFile
    * @author Maya Crawford
    public class Lab0
    * this function will prompt and receive data from the keyboard
    * @return String containing the data read from the keyboard
    * @param BufferedReader that is connected to System.in
    */ (keyboard)
    public static String getData(BufferedReader infile)
    throws IOException
    System.out.println("enter a name");
    return infile.readLine();
    * this is the main program which will read from the keyboard and
    * display the given input onto the screen and also write the data
    * to a file
    * @param Array of Strings (not used in this program)
    public static void main(String[] args)
    throws IOException
    int i;
    String[] outString = new String[16];
    DataOutputStream output=null;
    // this code assigns the standard input to a datastream
    BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
    // this code opens the output file...
    try
    output= new DataOutputStream(new FileOutputStream("javaapp.dat"));
    // handle any open errors
    catch (IOException e)
    System.err.println("Error in opening output file\n"
    + e.toString());
    System.exit(1);
    // priming read......
    for(i=0;i<outString.length;i++)
    outString=getData(input);
    // this is the loop to continue while nnonblank data is entered
    while (!outString.equals(""))
    for(i=0;i<outString.length;i++)
    outString[i]=getData(input);
    outString[i] = input.readLine();
    System.out.println("Name entered was:"+ outString[i]);
    output.writeBytes(outString[i]+"\r\n");
    int rcol=(outString.length+1)/2;
    for(i=0;i<(outString.length)/2;i++)
    System.out.println(outString[i]+"\t"+outString[rcol++]);
    // flush buffers and close file...
    try
    output.flush();
    output.close();
    catch (IOException e)
    System.err.println("Error in closing output file\n"
    + e.toString());
    // say goodnight Gracie...
    System.out.println("all done");

    Ok, here is what I came up with. I commented most of what I changed and gave a reason for changing it. My changes aren't perfect and it still needs to be tweeked. When you run the program you have to hit the enter key every time once before you type a name. When you are done typing names hit the enter key twice and it will output the names entered into the array. Like I said, it isn't perfect, and that part you will need to fix.
    import java.io.*;
    * the purpose of this program is to read data from the keyboard
    * and put it into a sequential file for processing by ReadFile
    * @author Maya Crawford
    public class Lab0
         * this function will prompt and receive data from the keyboard
         * @return String containing the data read from the keyboard
         * @param BufferedReader that is connected to System.in
         */ //(keyboard)
         //On the above line where you have (keyboard), it wasn't commented out in your
         //program and it was throwing a error.
         public static String getData(BufferedReader infile)
         throws IOException
              System.out.println("enter a name");
              return infile.readLine();
         * this is the main program which will read from the keyboard and
         * display the given input onto the screen and also write the data
         * to a file
         * @param Array of Strings (not used in this program)
         public static void main(String[] args)
         throws IOException
              int i;
              String testString; // Created to hold the string entered by the user, because your
                                 // outString array wasn't working for that.
              String[] outString = new String[16];
              DataOutputStream output=null;
              // this code assigns the standard input to a datastream
              BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
              // this code opens the output file...
              try
                   output= new DataOutputStream(new FileOutputStream("javaapp.dat"));
              // handle any open errors
              catch (IOException e)
                   System.err.println("Error in opening output file\n"
                   + e.toString());
                   System.exit(1);
              // priming read......
              testString = " ";  // Initialize testString
              int placeMark = 0; // to input the String entered by the user into the outString
                                 // array, it needs to know which position to enter it into.
              while (!testString.equals(""))
                   testString=getData(input);
                   testString = input.readLine();
                   System.out.println("Name entered was:"+ testString);
                   // Put the testString into the outString[] array.
                   // A lot of the time when you used outString you forgot to use the [x] to indicate
                   // which position you wanted to access.
                   outString[placeMark] = testString;
                   output.writeBytes(testString+"\r\n");
                   placeMark++;
            // Created a do/while loop to display the list of outString.
              int nextEntry = 0;
              do
                   System.out.println(outString[nextEntry]);
                   nextEntry++;
              }while(!outString[nextEntry].equals(""));
              // flush buffers and close file...
              try
                   output.flush();
                   output.close();
              catch (IOException e)
                   System.err.println("Error in closing output file\n"
                   + e.toString());
              // say goodnight Gracie...
              System.out.println("all done");
    }

  • Can you share the source code for Customer ToughDay stress test tool?

    Hello,
    I would like to try Customer ToughDay tool (http://dev.day.com/docs/en/cq/current/testing/tough-day.html) for load testing of our author instances of CQ5. While I am able to execute the application, the logging with log4j seems to be configured incorrectly.
    Can you share the source code for toughday-5.5.jar?  I think it can be a very good starting point for those of us who are new to CQ5 and need to load test it.
    Thank you!

    Hi,
    I don't believe there are any differences between the two versions. But you can check the source code for the Numeric Limit Test in TestStand\Components\NI\StepTypes\CommonSubsteps. But the main part of the step is the Code Module and this bit the users supplies this.
    What has prompted this question?
    Regards
    Ray Farmer
    Regards
    Ray Farmer

  • Can someone please post the password for the following HP Mini 110

      Customer brought in laptop and did remember the bios password.
    We tried the suggested download win32 to submit the halt code and it did not work on xp or win7 in compatibility mode.     Can someone please post the password for the following HP Mini 110. 
        Halt code = CNU937BF2X
    thanks  Andy  Mountain Computers Inc.

    Hi,
    Try:
    e9lofxp874
    e9lofxp87r

  • Select  all and dselect all can any body provide a code for these buttons

    hi
    i have taken 4 buttons for select  all and dselect all  and sort up and sort down can any body provide a code for these buttons.
    thanks

    hi,
    Refer this link...
    code for select_all and deselect_all in modulepool

  • Can someone suggest some good books for sql reporting services (SSRS) 2012 or above?

    Hi Everyone,
        Can someone suggest some good books for sql reporting services (SSRS) 2012 and above? I ave been working on ssrs for past 2 months and have a basic understanding of ssrs.
    Regards
    Regards

    Hi,
    you can look for below options;
    http://www.amazon.in/Microsoft-Server-Reporting-Services-Recipes/dp/0470563117#reader_0470563117
    http://www.goodreads.com/book/show/18147604-learning-sql-server-reporting-services-2012
    Thanks
    Please Mark This As Answer or vote for Helpful Post if this helps you to solve your question/problem. http://techequation.com

  • Can someone just spell it out for me?  Going from FCP HD to DVD SD :-(

    Hey folks. I hate to come here and ask a gargantuan number of questions, but this has been driving me out of my mind. I've tried asking specific question in hopes of simply finding one little problem that will fix my woes, but now it has come to this:
    Can someone just spell it out for me?
    How do I get my DVD going? I'll fill you in with all the knowlege I think you need.
    I shot with Sony's HDR-FX1 and edited in Final Cut. That means I'm working with High defintion. The movie is set and solid, and runs One hour and twenty mintues. I'm trying to get it, the commentary track, the subtitle track, and a slew of video files (also shot in high def) onto one dvd. This goes beyond the 4.8 gig limit. Hence, i have a Dual layer burner, and have been burning onto DVD-R DL disks.
    I've tried downgrading to SD format through steps from this website:
    http://www3.telus.net/bonsai/Step-by-Step.html
    I do all the steps to all of my files, and then start putting them into my DVD STUDIO PRO project. I have a recorded commentary which I add in, and I have written all the subtitles. The disk is in SD mode, and everything fits onto the dual layer disk. I've tried literally a dozen different ways, and something keeps going wrong. Either the menus won't come up, and just the film will play upon inserting, or the subtitle stream doesn't pick up- problem after problem. So, now I ask: Can someone simply spell out to me what steps I need to take to get my HD film onto a Dual Layer SD disk?
    I apologize for how general this question is and how many directions it can go, but I'm at a breaking point after four months of failures. Thank you very much.

    Hi man.
    I don't really know which ways you've taken to put
    the video into dvd studio, but since you're asking
    for a step by step process, then here's what i do:
    - export the entire hour out of FCP to a qt file
    - take that QT file to compressor. the only audio you
    really need is dolby 2.0. this would also reduce the
    file size of video to make things fit in a single
    layer dvd
    I have always found that the 'Dolby 2.0' and '5.1' AC3 settings in Compressor badly affect your audio mix...it collapses the soundstage, takes away a lot of depth and imaging, and smudges the frequency range, so I usually output a 16-bit 48kHz, which holds things together much more nicely when working with a stereo mix. Problem is, for a feature-length films, the resulting output from compressor makes it too big to fit on standard DVD-R's with the M2V picture file. My workaround was to actually take take the original exported FCP QT movie (which has a 48kHz aiff soundtrack to begin with), and only lay the audio part of it in the track timeline in DVD studio pro, then lay the compressed M2V video on top of it. They're both still in sync, unless you picked different in/out points in Compressor. When you 'build' your Video/Audio TS in 'advanced burn' it somehow makes it small enough to all fit onto a DVD, while still maintaining the audio quality of the AIFF, instead of the crappy-sounding 2.0 AC3. Then you just use Toast to burn your disc. The difference in sound quality is night and day. So basically I do the picture in Compressor, but let DVD Studio Pro prepare the audio in the Advanced Burn stage.
    It will be very difficult to get a good-sounding AC3 (what they call 'dolby' 2.0 or the wierd 5.1 encoding they use) unless you mix/master/encode your soundtrack professionally like regular studio films do. Just encoding it in compressor straight out of FCP or ProTools isn't enough. You lose too much.

  • Hello, I'm having trouble getting to the page where I can put in my activation code for my One to One. I keep getting ID or Password error. Have already reset twice- HELP Plz.

    Hello, I'm having trouble getting to the page where I can put in my activation code for my One to One. I keep getting ID or Password error. Have already reset twice… HELP Plz.

    sashaburg wrote:
    Unfortunately Netgear's support isn't very supportive.
    Without Airport set-up, and without wireless connection, I can't talk between macs either.
    Ok, this is a mac question: With the order changed so that the ethernet comes first, why is it still showing my connection to the neighbor's wireless? Am I reading that wrong? OR am I connected to both at the same time? If so, why would it connect twice to the internet?
    Probably because you neighbor has no security on his network. Does his network show a lock like
    If it does he's got security turned on, if there is no lock showing he hasn't turned it on.

Maybe you are looking for

  • Updating charts and datagrids based on selection

    I am trying to find some documentation and samples explaining how I can pick something in a combobox and have it populate a series of datagrids and charts. OUTLINE: A.  Using an XML table of all municipalities in our region populate a combobox.  Then

  • Running 8i and 10g on same UNIX server

    Greetings, I am a developer playing DBA, so please forgive me if these are elementary questions. I have no DBA support. I have a Solaris 8 server currently running operational software using 8i. My requirement is to load and test 64bit 10g without in

  • Class loader problem in 10.1.0.2.0

    I am using oracle.jar version 9.0.2.0.0 in my product, this oracle.jar don't have the classes like oracle/jdbc/driver/DatabaseError. In our new release of the same product we are decided to use 10.1.0.2.0, this is also works fine. When I upgrade my p

  • Inventory Report - Aging

    Dear Guru's Is there any way of finding out the aging of materials in stock. Regards, Lux

  • Offline Re-organization of database

    Hi We are using SAP CRM 4.0 ( ECC 5.0) on HPUX 11.23 and Oracle 9.2.0.6 as the database. I would like to carry out an offline reorganization of the database. What are the steps involved, Do I use brtools to do this activity. Some of my tables eg BALD