How to initiate connection with JDBC on OpenShift?

2019-06-13 16:52发布

问题:

When I work on my localhost , in order to initiate a connection with JDBC , I do this :

String USERNAME = "...";
String PASSWORD = "...";
String DB_NAME = "...";
String FORNAME_URL = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost";
Connection m_connection = DriverManager.getConnection(URL , USERNAME , PASSWORD);

But this doesn't work on OpenShift , no connection is established .

I can't see the exception that I'm getting when I run it on OpenShift ,but I validated (I checked the DB on OpenShift , it hasn't been updated with my queries) that the connection is not established

Any idea how to fix it ?

回答1:

This will not work on OpenShift because OpenSHift expose a set of environment variables that you have to use in your application. You can't use localhost, etc properties. Please use following:

String USERNAME = System.getEnv("OPENSHIFT_MYSQL_DB_USERNAME");
String PASSWORD = System.getEnv("OPENSHIFT_MYSQL_DB_PASSWORD");
String DB_NAME = System.getEnv("OPENSHIFT_APP_NAME");
String FORNAME_URL = "com.mysql.jdbc.Driver";
String URL = "jdbc:"+System.getEnv("OPENSHIFT_MYSQL_DB_URL")+ DB_NAME;
Connection m_connection = DriverManager.getConnection(URL , USERNAME , PASSWORD);


回答2:

What makes you think that your connection code isn't working? Could it be that your local database has some different option set by default (like autocommit) but the remote one doesn't?

Make sure your code is surrounded by a try/catch and any exceptions are logged. If you don't get an exception then it's working fine.