我设法用phpMyAdmin等在OpenShift上设置MySQL数据库。有人告诉我我数据库的主机名和端口 分别是$ OPENSHIFT_MYSQL_DB_HOST和$OPENSHIFT_MYSQL_DB_PORT,将它们放在我的context.xml文件中, 如下所示:
<context-param> <param-name>driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/burgerjoint</param-value> </context-param> <context-param> <param-name>user</param-name> <param-value>admin******</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value>*********</param-value> </context-param>
设置连接的代码是:
public void contextInitialized(ServletContextEvent event) { // Connect String driver = event.getServletContext().getInitParameter(PARAM_DRIVER); String url = event.getServletContext().getInitParameter(PARAM_URL); String username = event.getServletContext().getInitParameter(PARAM_USERNAME); String password = event.getServletContext() .getInitParameter(PARAM_PASSWORD); try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); event.getServletContext().setAttribute(ATTR_CONNECTION, connection); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
但是问题是服务器上的连接为空,我不明白为什么。我做错什么了吗?当我在localhost 上尝试时,该代码有效。据我所知,我拥有所有必需的库:
谢谢您的帮助 :)
更新资料
我修改了连接代码,如下所示:
{ if (connection != null) return connection; try { Properties dbProperties = new Properties(); InputStream input = DatabaseUtil.class.getClassLoader().getResourceAsStream(DB_PROPERTIES_FILE); dbProperties.load(input); String url = ""; if (appIsDeployed) { String host = System.getenv("$OPENSHIFT_MYSQL_DB_HOST"); String port = System.getenv("$OPENSHIFT_MYSQL_DB_PORT"); String name = "burgerjoint"; url = "jdbc:mysql://" + host + ":" + port + "/" + name; } else { url = dbProperties.getProperty(PARAM_URL); } String driver = dbProperties.getProperty(PARAM_DRIVER); String username = dbProperties.getProperty(PARAM_USERNAME); String password = dbProperties.getProperty(PARAM_PASSWORD); Class.forName(driver); connection = DriverManager.getConnection(url, username, password);
but it still gives null connection. The values of System.getenv("$OPENSHIFT_MYSQL_DB_HOST") and System.getenv("$OPENSHIFT_MYSQL_DB_PORT") are null.
System.getenv("$OPENSHIFT_MYSQL_DB_HOST")
System.getenv("$OPENSHIFT_MYSQL_DB_PORT")
This is incorrect:
jdbc:mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/burgerjoint
That dollar sign suggests that you think a proper host and database name will be substituted, but that’s not the case.
Code the host and database name to see that it works, then learn about .properties files to externalize it.