New*_*ser 6 mysql jsp database-connection
我刚刚踏上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>
Run Code Online (Sandbox Code Playgroud)
我收到消息,因为连接状态无法连接到数据库.我PHP使用相同的用户名,密码和数据库名称测试了此连接.我哪里弄错了?
原因是驱动程序尚未加载到库中,它没有在连接中实例化,因此连接失败:
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);
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题.我非常清楚你的程序有什么问题:你没有将.jar添加到web lib.复制并粘贴到WEB-INF/lib中.
很抱歉没有使用正确的格式发布答案(我是新来的,这是我的第一个anwser :()
| 归档时间: |
|
| 查看次数: |
59626 次 |
| 最近记录: |