我正在尝试使用以下servlet建立与数据库的连接:(工作在doGet方法中完成)
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Connect")
public class Connect extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Connect() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
out.println("Unable to load database.");
return;
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
//// Connected to database. do some work here ////////////
out.println("Connected to the database!");
///////////////////////////////////////////////////////////
try {
conn.close();
} catch (SQLException e) {
out.println("Unable to close connection to database.");
}
}
}
然而,我总是被挂断
try {
conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/jakesdb", "root", "sixTeen58");
} catch (SQLException e) {
out.println("Unable to connect to the database.");
return;
}
我已经使用sql workbench验证了用户名(root)和密码(sixTeen58)是否正确,并且端口确实是3306.我的库中有mysql-connector-java-5.1.36.zip并且链接正确。我不确定发生了什么,但每次我在运行页面时都看到“无法连接到数据库”。
知道我做错了吗?
答案 0 :(得分:0)
你犯了一个小错误。您需要在:
方法的数据库URL处使用冒号.
而不是getConnection
。改变如:
"jdbc:mysql://localhost:3306/jakesdb" // Use : instead of .