我设法使用 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);
但它仍然提供空连接。System.getenv("$OPENSHIFT_MYSQL_DB_HOST")
和的值为System.getenv("$OPENSHIFT_MYSQL_DB_PORT")
空。