我设法用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”)的值为空.
解决方法:
这是不正确的:
jdbc:MysqL://$OPENSHIFT_MysqL_DB_HOST:$OPENSHIFT_MysqL_DB_PORT/burgerjoint