java.lang.ClassNotFoundException:com.microsoft.jdbc.sqlserver.SQLServerDriver:我加载了正确的驱动程序吗?

Y.E*_*E.P 3 java sql-server datasource jdbc classnotfoundexception

当我运行以下代码片段连接到数据源以通过查询获取数据时:

        try {
        String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
        Class.forName(driver);
        String Url = "jdbc:sqlserver://localhost:1433;databaseName=movies";
        Connection connection = DriverManager.getConnection(Url,"sa", "xxxxxxx);
        //            Context initContext = new InitialContext();
        //            Context envContext = (Context)initContext.lookup("java:comp/env");
        //            DataSource ds = (DataSource)envContext.lookup("");
        //            Connection connection = ds.getConnection();
        String query_name = "select name from list where name='" + data + "'";
Run Code Online (Sandbox Code Playgroud)

显示此异常跟踪:

java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at gui.MainGui.startSqlServerDataSearch(MainGui.java:148)
at gui.MainGui$3.run(MainGui.java:129)
at java.lang.Thread.run(Thread.java:619)
Run Code Online (Sandbox Code Playgroud)

为什么我得到这个例外?我已经连接到sql server(通过加载这里给出的驱动程序)并且可以看到sql server中定义的数据库.以下快照说明了这一点:

在此输入图像描述

kos*_*osa 9

定义了数据库Class.forName(driver); 是不足够的.

您需要确保适当的数据库驱动程序jar在类路径中.

  • @YEP将驱动程序字符串更改为`com.microsoft.sqlserver.jdbc.SQLServerDriver`而不是`com.microsoft.jdbc.sqlserver.SQLServerDriver` (10认同)