我有一个 servlet 类,我在其中建立了与MySQL
数据库的连接。这是我的doGet()
方法代码。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","rspl123#");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(con);
response.getWriter().write(request.getParameter("q"));
}
对于上面的代码,当第一次调用 servlet 时,会抛出异常No suitable driver found
。但它第二次运行并成功建立连接。
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at controller.FetchSuggestion.doGet(FetchSuggestion.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)
null
com.mysql.jdbc.JDBC4Connection@1b83048
com.mysql.jdbc.JDBC4Connection@1455d1c
com.mysql.jdbc.JDBC4Connection@1f51e5c
如果我从 中删除评论,上面的代码可以正常Class.forName()
工作,但如果没有它第一次它就无法工作并且能够第二次建立连接。仅供参考:我的课程路径中已经有 MySQL JAVA 连接器。
MySQL Java 连接器版本:5.1.10
JDK:1.6
IDE:MyEclipse for Spring