【问题标题】:How to Load Mysql class Driver in java [duplicate]如何在java中加载Mysql类驱动程序[重复]
【发布时间】:2016-01-15 08:00:14
【问题描述】:

我有以下代码,其中我得到类未找到 com 的异常。 mysql.jdbc.驱动程序。我该怎么办?

    try {
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dimple?zeroDateTimeBehavior=convertToNull", "root", "password");
        PreparedStatement ps = con.prepareStatement("Insert Into data Values(? ,? )");
        ps.setString(1, name);
        ps.setString(2, pass);
       int f =  ps.executeUpdate();
       if(f>0)
       {
           out.println("Successfuly inserted");
           RequestDispatcher rd = request.getRequestDispatcher("index.html");
           rd.forward(request, response);
       }
       else
           out.println("Not inserted");

    }
    catch(Exception e)
    {
        out.println(e);
    }

【问题讨论】:

    标签: java mysql servlets


    【解决方案1】:

    包含 com.mysql.jdbc.Driver 类的 MySql jar 库必须在您的类路径中。

    在此处查看可下载的 MySql 驱动程序:

    MySql JDBC Drivers

    【讨论】:

    • +1 如果您使用的是 Eclipse 或任何 IDE,最好将此 JAR 包含在项目的构建路径中。另外,在不同的注释上-使用字符数组而不是字符串作为密码可能是更好的实现。见:stackoverflow.com/questions/8881291/…
    • 非常感谢您的帮助..
    【解决方案2】:

    您应该首先下载驱动程序 jar 文件并将其添加到您的项目类路径中,然后加载该类。

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    // Notice, do not import com.mysql.jdbc.*
    // or you will have problems!
    
    public class LoadDriver {
        public static void main(String[] args) {
            try {
                // The newInstance() call is a work around for some
                // broken Java implementations
    
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (Exception ex) {
                // handle the error
            }
        }
    }
    

    完成这些步骤后,您可以像以前一样使用驱动程序。

    更多信息:

    【讨论】:

    • 我已经实现了,但是在加载类的驱动程序时出错,驱动程序类名出现 cLassNOTFound 异常...
    • 但仍然感谢您的帮助
    • @Dimple 您应该在项目类路径中包含 MySql 驱动程序 jar 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2019-06-23
    • 2018-12-07
    • 2014-08-19
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多