从JSP连接MySQL

问题描述 投票:0回答:4

我刚刚踏上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 测试了此连接。我哪里出错了?

    

mysql jsp database-connection
4个回答
9
投票

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); }

下载驱动程序


5
投票

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


2
投票

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

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


0
投票

我的就是这样工作的!

© www.soinside.com 2019 - 2024. All rights reserved.