How to check the connection status in java using jdbc connection?2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java

Employee lack of ownership

How Could an Airship Be Repaired Mid-Flight

How could a scammer know the apps on my phone / iTunes account?

Could the Saturn V actually have launched astronauts around Venus?

How to deal with taxi scam when on vacation?

Knife as defense against stray dogs

How can I track script which gives me "command not found" right after the login?

What exactly is this small puffer fish doing and how did it manage to accomplish such a feat?

How to create the Curved texte?

Sailing the cryptic seas

It's a yearly task, alright

What should tie a collection of short-stories together?

How to read the value of this capacitor?

Are ETF trackers fundamentally better than individual stocks?

Why did it take so long to abandon sail after steamships were demonstrated?

Are all passive ability checks floors for active ability checks?

Min function accepting varying number of arguments in C++17

Bach's Toccata and Fugue in D minor breaks the "no parallel octaves" rule?

Can a druid choose the size of its wild shape beast?

Do I need to be arrogant to get ahead?

What has been your most complicated TikZ drawing?

Should we release the security issues we found in our product as CVE or we can just update those on weekly release notes?

How to terminate ping <dest> &

If I can solve Sudoku can I solve Travelling Salesman Problem(TSP)? If yes, how?



How to check the connection status in java using jdbc connection?



2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java










-2















How to handle sql exceptions in Msaccess jdbc connection? I'm retrieving data from msaccess using jdbc connection in java. If connection fail i need to show-up the custom message instead of throwing exception.



public static Connection getConnection() 
Connection connection = null;
try

String url = "jdbc:odbc:db1";
String username = "";
String password = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection= DriverManager.getConnection(url, username, password);

catch(Exception e)

System.out.println("Report");

return connection;



But its not handling the custom message.its throwing error :
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object










share|improve this question



















  • 2





    Have you tried catching exception?

    – Petro Semeniuk
    Dec 18 '12 at 1:55















-2















How to handle sql exceptions in Msaccess jdbc connection? I'm retrieving data from msaccess using jdbc connection in java. If connection fail i need to show-up the custom message instead of throwing exception.



public static Connection getConnection() 
Connection connection = null;
try

String url = "jdbc:odbc:db1";
String username = "";
String password = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection= DriverManager.getConnection(url, username, password);

catch(Exception e)

System.out.println("Report");

return connection;



But its not handling the custom message.its throwing error :
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object










share|improve this question



















  • 2





    Have you tried catching exception?

    – Petro Semeniuk
    Dec 18 '12 at 1:55













-2












-2








-2


0






How to handle sql exceptions in Msaccess jdbc connection? I'm retrieving data from msaccess using jdbc connection in java. If connection fail i need to show-up the custom message instead of throwing exception.



public static Connection getConnection() 
Connection connection = null;
try

String url = "jdbc:odbc:db1";
String username = "";
String password = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection= DriverManager.getConnection(url, username, password);

catch(Exception e)

System.out.println("Report");

return connection;



But its not handling the custom message.its throwing error :
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object










share|improve this question
















How to handle sql exceptions in Msaccess jdbc connection? I'm retrieving data from msaccess using jdbc connection in java. If connection fail i need to show-up the custom message instead of throwing exception.



public static Connection getConnection() 
Connection connection = null;
try

String url = "jdbc:odbc:db1";
String username = "";
String password = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection= DriverManager.getConnection(url, username, password);

catch(Exception e)

System.out.println("Report");

return connection;



But its not handling the custom message.its throwing error :
java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object







java ms-access






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 14:17









Wojciech Wirzbicki

1,50011325




1,50011325










asked Dec 18 '12 at 1:50









user441978user441978

42071428




42071428







  • 2





    Have you tried catching exception?

    – Petro Semeniuk
    Dec 18 '12 at 1:55












  • 2





    Have you tried catching exception?

    – Petro Semeniuk
    Dec 18 '12 at 1:55







2




2





Have you tried catching exception?

– Petro Semeniuk
Dec 18 '12 at 1:55





Have you tried catching exception?

– Petro Semeniuk
Dec 18 '12 at 1:55












3 Answers
3






active

oldest

votes


















1














The location where you are calling getConnection, provide custom message there by handling exception:



Connection con = null;
try
con = DatabaseUtil.getConnection();
...
...
catch(Exception e)
//show message, dialog box, whatever
finally
if(con != null)
try
con.close();
catch(SQLException sqe)
//yet another message, unable to close connection cleanly.





P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection



P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).






share|improve this answer






























    1














    You can not avoid exceptions. Instead of throwing them, you can handle them by using



     try
    // do Something
    catch(SqlException e)
    // catch exception
    finally
    // do something to get recover



    For more info follow this link






    share|improve this answer






























      1














      You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.



      To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.



      However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.






      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13925151%2fhow-to-check-the-connection-status-in-java-using-jdbc-connection%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        1














        The location where you are calling getConnection, provide custom message there by handling exception:



        Connection con = null;
        try
        con = DatabaseUtil.getConnection();
        ...
        ...
        catch(Exception e)
        //show message, dialog box, whatever
        finally
        if(con != null)
        try
        con.close();
        catch(SQLException sqe)
        //yet another message, unable to close connection cleanly.





        P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection



        P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).






        share|improve this answer



























          1














          The location where you are calling getConnection, provide custom message there by handling exception:



          Connection con = null;
          try
          con = DatabaseUtil.getConnection();
          ...
          ...
          catch(Exception e)
          //show message, dialog box, whatever
          finally
          if(con != null)
          try
          con.close();
          catch(SQLException sqe)
          //yet another message, unable to close connection cleanly.





          P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection



          P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).






          share|improve this answer

























            1












            1








            1







            The location where you are calling getConnection, provide custom message there by handling exception:



            Connection con = null;
            try
            con = DatabaseUtil.getConnection();
            ...
            ...
            catch(Exception e)
            //show message, dialog box, whatever
            finally
            if(con != null)
            try
            con.close();
            catch(SQLException sqe)
            //yet another message, unable to close connection cleanly.





            P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection



            P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).






            share|improve this answer













            The location where you are calling getConnection, provide custom message there by handling exception:



            Connection con = null;
            try
            con = DatabaseUtil.getConnection();
            ...
            ...
            catch(Exception e)
            //show message, dialog box, whatever
            finally
            if(con != null)
            try
            con.close();
            catch(SQLException sqe)
            //yet another message, unable to close connection cleanly.





            P.S. Its a bad idea to declare "Exception", you should always try to throw most relevant exception from your method. SQLException makes more sense in DatabaseUtil.getConnection



            P.P.S. Class.forName(driver); is only required once per JVM invocation (for JDBC driver registration). Hence, the appropriate place to register your JDBC drivers is in a static initializer (which is called once when your class is loaded for the first time).







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 18 '12 at 2:52









            Usman SaleemUsman Saleem

            1,549815




            1,549815























                1














                You can not avoid exceptions. Instead of throwing them, you can handle them by using



                 try
                // do Something
                catch(SqlException e)
                // catch exception
                finally
                // do something to get recover



                For more info follow this link






                share|improve this answer



























                  1














                  You can not avoid exceptions. Instead of throwing them, you can handle them by using



                   try
                  // do Something
                  catch(SqlException e)
                  // catch exception
                  finally
                  // do something to get recover



                  For more info follow this link






                  share|improve this answer

























                    1












                    1








                    1







                    You can not avoid exceptions. Instead of throwing them, you can handle them by using



                     try
                    // do Something
                    catch(SqlException e)
                    // catch exception
                    finally
                    // do something to get recover



                    For more info follow this link






                    share|improve this answer













                    You can not avoid exceptions. Instead of throwing them, you can handle them by using



                     try
                    // do Something
                    catch(SqlException e)
                    // catch exception
                    finally
                    // do something to get recover



                    For more info follow this link







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 18 '12 at 1:56









                    SmitSmit

                    4,20112027




                    4,20112027





















                        1














                        You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.



                        To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.



                        However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.






                        share|improve this answer





























                          1














                          You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.



                          To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.



                          However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.






                          share|improve this answer



























                            1












                            1








                            1







                            You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.



                            To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.



                            However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.






                            share|improve this answer















                            You cannot avoid the SQLException being thrown. The JDBC APIs don't provide a method to test connection liveness.



                            To test if a JDBC connection is (still) valid, you perform a simple query. The "dummy query" idiom for doing this varies with the database, but any query on any of your tables will suffice. If the connection is not alive you will get an exception ... which you need to handle.



                            However it is possible for the database connection to die between you testing the connection and then performing your real query (or whatever). So (IMO) you are better off just writing your code so that it can deal with the SQLException in a real query ... and not bother probing. This also gives better performance, because repeatedly testing to see if a JDBC connection is alive is going to add useless load to your application ... and the database.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 19 '12 at 3:10

























                            answered Dec 18 '12 at 2:45









                            Stephen CStephen C

                            523k72582942




                            523k72582942



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13925151%2fhow-to-check-the-connection-status-in-java-using-jdbc-connection%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                                Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                                How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page