【问题标题】:Driver for jdbc not found (only on servlet)找不到 jdbc 的驱动程序(仅在 servlet 上)
【发布时间】:2014-10-11 01:28:47
【问题描述】:

我从 servlet 连接到 MySQL 数据库时遇到问题。这是我的连接代码

private static void connectToDatabase(){
    try{
        static Connection conn = null;
        static String url = "jdbc:mysql://localhost/database?userinfo"; 
        conn = DriverManager.getConnection(url);
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connected");
    } catch(ClassNotFoundException wyjatek) {
        System.out.println("Problem ze sterownikiem");
    } catch(SQLException wyjatek) {
        System.out.println("SQLException: " + wyjatek.getMessage());
        System.out.println("SQLState: " + wyjatek.getSQLState());
        System.out.println("VendorError: " + wyjatek.getErrorCode());
    }
}

和doGet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    String param = request.getParameter("lookFor");

    out.println("TEST");

    connectToDatabase();
 }

每次我得到这个

SQLException: No suitable driver found for jdbc:mysql://localhost/database?userinfo
SQLState: 08001
VendorError: 0

我把 mysql-connector-java-5.1.27-bin 放进去 webapps\WEB-INF\lib 和 apache-tomcat-7.0.55\lib

它仍然是一样的。在应用程序的桌面版本中,一切正常。它只发生在 servlet 上。

【问题讨论】:

  • 你在tomcat/lib中放了哪个jar?
  • 只把mysql-connector-java-5.1.27-bin放到lib里面是不行的,你在classpath里加了吗?
  • 不应该通过app/container XML配置吗?
  • 尝试调用Class.forName("com.mysql.jdbc.Driver")之前调用DriverManager.getConnection(url)
  • @scarywombat mysql-connector-java-5.1.27-bin.jar

标签: java mysql servlets jdbc


【解决方案1】:

基本问题是

您的第一步应该是使用此注册驱动程序

Class.forName("com.mysql.jdbc.Driver");

然后尝试使用这个从 DriverManager 获取连接

conn = DriverManager.getConnection(url);

我猜你正在做相反的方式

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 2015-06-15
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2012-02-05
    相关资源
    最近更新 更多