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

                                Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                                Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived