从 JSP 连接 MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13505833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting MySQL from JSP
提问by NewUser
I just set foot on JSP. I started writing simple programs to display dates, system info. Then I tried to connect a MySQL database
I have a free hosting account, but I am not able to connect to MySQL database. Here is my code:
我刚踏上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>
I am getting Message as Connection Status unable to connect to database. I have tested this connection using PHP
using the same username, password and database name. Where am I making mistake?
我收到消息,因为连接状态无法连接到数据库。我已经PHP
使用相同的用户名、密码和数据库名称测试了这个连接。我哪里出错了?
回答by gks
Reason is the driver have not been loaded in the libraries, it does not get instantiated in the connection so the connection failed:
原因是驱动程序尚未加载到库中,它没有在连接中实例化,因此连接失败:
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);
}
回答by tartaruga_casco_mole
I‘ve got the same problem. I'm pretty much sure what's wrong with your program: you haven't added .jar to web lib. Copy it and paste into WEB-INF/lib.
我有同样的问题。我很确定你的程序有什么问题:你没有将 .jar 添加到 web lib。将其复制并粘贴到 WEB-INF/lib 中。
Sorry for not using the correct format for posting answers(I'm new here and this is my first anwser:( )
很抱歉没有使用正确的格式来发布答案(我是新来的,这是我的第一个答案:()
回答by Alexandre Lavoie
Download the right driver :
下载正确的驱动程序:
http://dev.mysql.com/downloads/connector/j/
http://dev.mysql.com/downloads/connector/j/
And add the jar in the classpath of your project.
并将 jar 添加到项目的类路径中。