简体   繁体   English

如何使用Java测试与Oracle数据库的连接

[英]How to test connection to Oracle Database using Java

Is there a way to test my connection to oracle database using Java? 有没有办法使用Java测试我与oracle数据库的连接? Here's my code. 这是我的代码。

public class OracleConnection {

    public static void main(String[] args) throws Exception {
        //connect to database
        Class.forName("oracle.jdbc.driver.OracleDriver");
        String serverName = "00.000.0.000";
        String portNumber = "1521";
        String sid = "My Sid";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String username = "UNAME";
        String password = "PASSWORD";
        Connection conn = DriverManager.getConnection(url, username, password);
    }
}

What I want to do is test the database if it is reachable and if its not then the program will connect to the next database. 我想要做的是测试数据库是否可以访问,如果不可以,那么程序将连接到下一个数据库。 I have 8 production database. 我有8个生产数据库。

DriverManager#getConnection it self attempts to establish a connection to the given database URL. DriverManager#getConnection它自己尝试建立与给定数据库URL的连接。 The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers. DriverManager尝试从已注册的JDBC驱动程序集中选择适当的驱动程序。 and thorws SQLException if a database access error occurs. 和thorws SQLException如果发生数据库访问错误。

you can test you connection is valid or not with Connection#isValid(int timeout) returns true if the connection has not been closed and is still valid. 您可以测试连接是否有效Connection#isValid(int timeout)如果连接尚未关闭且仍然有效,则返回true。

...
Connection conn = DriverManager.getConnection(url, username, password);
boolean reachable = conn.isValid(10);// 10 sec

Simple Java code to check connection to Oracle DB: 用于检查与Oracle DB的连接的简单Java代码:

import java.sql.*;    
public class Test {
  private final static String DB_URL = "jdbc:oracle:thin:@//192.168.1.105:1521/MYORA";
  private final static String USER = "myuser";
  private final static String PASS = "mypwd";

  public static void main(String[] args) {
    Connection conn = null;  
    try {    
      Class.forName("oracle.jdbc.driver.OracleDriver");    
      System.out.println("Connecting to database...");    
      conn = DriverManager.getConnection(DB_URL,USER,PASS);    
    } catch (Exception e) {    
      e.printStackTrace();    
    } finally {    
      if (conn != null) {    
        try {    
          conn.close();    
        } catch (SQLException e) {    
          // ignore    
        }    
      }    
    }            
  }    
}

Don't reinvent the wheel. 不要重新发明轮子。 Oracle's JDBC driver already has this functionality built-in. Oracle的JDBC驱动程序已经内置了此功能。

This is useful: http://www.orafaq.com/wiki/JDBC 这很有用: 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). 上面的代码实际上构建并使用看起来像这样的url(如下例所示)。 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)))

I wrote a mini command line app to do what above code samples do. 我写了一个迷你命令行应用程序,以执行上面的代码示例。

https://github.com/aimtiaz11/oracle-jdbc-tester https://github.com/aimtiaz11/oracle-jdbc-tester

Saves anyone coding it up. 保存任何编码的人。 Just build (with maven) and run it. 只需构建(使用maven)并运行它。

You can have an array of the your database server ips and iterate over them. 您可以拥有数据库服务器ips的数组并迭代它们。 For every failed connection attempt, you can proceed to the next ip from the array and try again. 对于每次失败的连接尝试,您可以从阵列继续执行下一个ip,然后重试。 In case of a successful connection, you break the loop there and use the current connection which was established. 如果连接成功,则在那里断开循环并使用已建立的当前连接。

Maybe you should ping the IP address of the server. 也许你应该ping服务器的IP地址。 You should check this out: Ping function returns that all pinged IP addresses is reachable 您应该检查一下: Ping函数返回所有ping的IP地址都可以访问

You can catch SQLException from DriverManager.getConnection() and looks for ORA-12543 . 您可以从DriverManager.getConnection()捕获SQLException并查找ORA-12543
Read SQLException documentation about vendor code. 阅读有关供应商代码的SQLException文档。

Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(“url”,”username”,”password ″); 

look more at here: http://leezk.com/tag/jdbc 在这里看看更多: http//leezk.com/tag/jdbc

" ... 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 . (我自己也没试过。)查看RAC环境的Oracle连接字符串

For testing connection i will create and use 2 methods: for connection to db and for test this connection: 为了测试连接,我将创建并使用两种方法:连接到db并测试此连接:

Class Connector {
private static final String CONNECTION_STRING = "jdbc:oracle:thin:@//%s:%d/%s";
private static final String QUERY_IS_CONNECTED = "SELECT * FROM table WHERE field = 'example'";
private static final Log LOG = LogFactory.getLog(Connector.class);

public Connection createConnection() {
    Connection connection = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        connection = DriverManager.getConnection(String.format(CONNECTION_STRING, "127.0.0.1", "1521", "dbName"), "userName", "password");
    } catch (Exception e) {
        LOG.error("createConnection: connection error");
    }

 return connection;
}

public boolean isConnected() {

        try (Connection connection = createConnection()) {
            if (connection.isClosed()) {
                    return false;
            }

            try (Statement statement = connection.createStatement();
                 ResultSet resultSet = statement.executeQuery(QUERY_IS_CONNECTED)) {
                if (resultSet == null) {
                    return false;
                }
            } catch (Exception e) {
                LOG.error("isConnected: Query error", e);
                return false;
            }
        } catch (Exception e) {
            LOG.error("isConnected: Check connection error", e);
            return false;
        }

        return true;
    }
}

createConnection() - default connection to your db. createConnection() - 与数据库的默认连接。 Values of ip,port,dbName,userName and password will be yours. ip,port,dbName,userName和password的值将是您的。

isConnected() - first part check correct your connection and second part checks the correctness of working with the database. isConnected() - 第一部分检查更正您的连接,第二部分检查使用数据库的正确性。 As there can be a connection, but not to be access for requests. 因为可以有连接,但不能访问请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM