【问题标题】:Connecting MySQL from JSP从 JSP 连接 MySQL
【发布时间】:2012-11-22 04:19:43
【问题描述】:

我刚刚涉足JSP。我开始编写简单的程序来显示日期、系统信息。然后我尝试连接MySQL database 我有一个免费的主机帐户,但我无法连接到 MySQL 数据库。这是我的代码:

<%@ page import="java.sql.*" %> 
<%@ page import="java.io.*" %> 
<html> 
<head> 
<title>Connection with mysql database</title>
</head> 
<body>
<h1>Connection status</h1>
<% 
try {
    String connectionURL = "jdbc:mysql://mysql2.000webhost.com/a3932573_product";
    Connection connection = null; 
    Class.forName("com.mysql.jdbc.Driver").newInstance(); 
    connection = DriverManager.getConnection(connectionURL, "a3932573_dibya", "******");
    if(!connection.isClosed())
         out.println("Successfully connected to " + "MySQL server using TCP/IP...");
    connection.close();
}catch(Exception ex){
    out.println("Unable to connect to database.");
}
%>
</font>
</body> 
</html>

我收到消息为连接状态无法连接到数据库。我已经使用PHP 使用相同的用户名、密码和数据库名称测试了此连接。我在哪里犯错了?

【问题讨论】:

  • 你的JSP服务器和PHP服务器是在同一台机器上吗?
  • 请在 catch 中打印出来并告诉我 ex.printStackTrace();
  • 我在连接状态之前得到一个 字符。
  • 赌 10$ 驱动程序未加载
  • 我编辑了问题,请检查 catch 块并显示完整的异常。

标签: mysql jsp database-connection


【解决方案1】:

原因是驱动程序没有加载到库中,它没有在连接中实例化,所以连接失败:

try {
            String connectionURL = "jdbc:mysql://host/db";
            Connection connection = null; 
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            connection = DriverManager.getConnection(connectionURL, "username", "password");
            if(!connection.isClosed())
                 out.println("Successfully connected to " + "MySQL server using TCP/IP...");
            connection.close();
        }catch(Exception ex){
            out.println("Unable to connect to database"+ex);
        }   

Download Driver

【讨论】:

    【解决方案2】:

    我也遇到了同样的问题。我很确定你的程序出了什么问题:你没有将 .jar 添加到 web lib。将其复制并粘贴到 WEB-INF/lib 中。

    很抱歉没有使用正确的格式来发布答案(我是新来的,这是我的第一个答案:()

    【讨论】:

      【解决方案3】:

      下载正确的驱动程序:

      http://dev.mysql.com/downloads/connector/j/

      并在项目的类路径中添加 jar。

      【讨论】:

        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多