How to test connection to Oracle Database using Java

后端 未结 10 1665
迷失自我
迷失自我 2021-02-04 09:56

Is there a way to test my connection to oracle database using Java? Here\'s my code.

public class OracleConnection {

    public static void main(String[] args)          


        
相关标签:
10条回答
  • 2021-02-04 10:47

    You can catch SQLException from DriverManager.getConnection() and looks for ORA-12543.
    Read SQLException documentation about vendor code.

    0 讨论(0)
  • 2021-02-04 10:49

    "... and if its not then the program will connect to the next ..." I wonder if a cluster connection string containing multiple server addresses could work for you. (I did not try this myself.) Look at Oracle Connection String for RAC Environment.

    0 讨论(0)
  • 2021-02-04 10:50

    Don't reinvent the wheel. Oracle's JDBC driver already has this functionality built-in.

    This is useful: http://www.orafaq.com/wiki/JDBC

    import java.util.ArrayList;
    import java.sql.*;
    
    public class OracleConnection {
    
        public static void main(String[] args) throws Exception {
            //connect to database
            Class.forName("oracle.jdbc.driver.OracleDriver");
            ArrayList<String> serverNames = new ArrayList<String>();
            serverNames.add("yourhostname1");
            serverNames.add("yourhostname2");
            serverNames.add("yourhostname3");
            serverNames.add("yourhostname4");
            String portNumber = "1521";
            String sid = "ORCLSID";
            String url = "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)" ;
            for (String serverName : serverNames) {  
                url += "(ADDRESS=(PROTOCOL=tcp)(HOST="+serverName+")(PORT="+portNumber+"))";
            }
            url += ")(CONNECT_DATA=(SID="+sid+")))";
            String username = "USERNAME";
            String password = "PASSWORD";
            // System.out.println(url); // for debugging, if you want to see the url that was built
            Connection conn = DriverManager.getConnection(url, username, password);
        }
    }
    

    The above code actually builds and uses url that looked like this (as example belows). I got this explicitly by uncommenting the debugging line near the end of the code:

    jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=
        (LOAD_BALANCE=ON)(FAILOVER=ON)
        (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname1)(PORT=1521))
        (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname2)(PORT=1521))
        (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname3)(PORT=1521))
        (ADDRESS=(PROTOCOL=tcp)(HOST=yourhostname4)(PORT=1521))
      )(CONNECT_DATA=(SID=ORCLSID)))
    
    0 讨论(0)
  • 2021-02-04 10:50
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection(“url”,”username”,”password ″); 
    

    look more at here:http://leezk.com/tag/jdbc

    0 讨论(0)
提交回复
热议问题