How to test connection to Oracle Database using Java

后端 未结 10 1685
迷失自我
迷失自我 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:42

    For testing connection i will create and use 2 methods: for connection to db and for test this connection:

    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. Values of ip,port,dbName,userName and password will be yours.

    isConnected() - first part check correct your connection and second part checks the correctness of working with the database. As there can be a connection, but not to be access for requests.

提交回复
热议问题