Openshift MysQL Tomcat连接为空

时间:2015-10-14 22:18:59

标签: java mysql tomcat database-connection openshift

我是Openshift的新手,尝试托管我的应用程序,但无法连接到Openshift中的MySQL数据库。

这是我连接MySQL的代码:

public class DBUtill {

public Connection getConnection() {

    String url = "jdbc:mysql://127.2.191.130:3306/database";
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }
    Connection con = null;
    try {
        con = DriverManager.getConnection(url, "user", "password");
    } catch (SQLException e) {

        e.printStackTrace();
    }
    return con;
}

public static void closeConnection(Connection conn) {
    try {
        conn.close();
    } catch (Exception e) {
        e.getMessage();
    }
}

但它不起作用,因为我总是得到con = null

但是当我将相同的代码直接放在jsp页面中时,一切正常:

<%@page import="com.java.testapp.db.DBUtill"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.SQLException"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<% 

    String url = "jdbc:mysql://127.2.191.130:3306/database";
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {

        e.printStackTrace();
    }
    Connection con = null;
    try {
        con = DriverManager.getConnection(url, "user", "password");
    } catch (SQLException e) {

        e.printStackTrace();
    }

DBUtill utill = new DBUtill();

out.println( "Connection: " +utill.getConnection()); // CONNECTION = null

out.println( "Connection: " +con); // IT WORKS!


%>

</body>
</html>

我不明白为什么在使用DBUtill类连接到MySQL时我得到con = null。但是连接在jsp中完全可以直接工作。 请帮忙

0 个答案:

没有答案