首页 > 解决方案 > java.sql.SQLException: 找不到合适的驱动程序 (SQL Server Express)

问题描述

我快疯了,现有的解决方案似乎都不适合我。我是老派,所以只需在 NotePad++/EditPlus 中编码并通过 CLI 编译。我有一个超级通用的 DB.JAVA 文件,我无法通过加载 SQL 驱动程序类的尝试。我很茫然,希望其他人可以提供帮助。从长远来看,这将在 Tomcat 上的 JSP 中使用。

Java 版本:1.8.0_181 或 10.0.2(我都有,x64 版本)

SQL Server : 2017 速成版

JDBC JAR:mssql-jdbc-6.4.0.jre8.jar(目前在与 DB.java 相同的目录中)

我的基本代码

import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;

public class DB {

    public static void main(String[] args) {

        // Create a variable for the connection string.
        String connectionURL = "jdbc:microsoft:sqlserver://HomeServer:1433;databaseName=MY_FIRST_DB";

        // Declare the JDBC objects.
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // I've read this isn't needed anymore as the DriverManager is smart enough
            // It will fail on this line, or the next if I comment it out with the same error
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(connectionURL,"sa","xxxxxxxxxxxx");

            // Create and execute an SQL statement that returns a
            // set of data and then display it.
            String SQL = "SELECT * FROM v_Users";
            stmt = con.createStatement();
            rs = stmt.executeQuery(SQL);
            while (rs.next()) {
                System.out.println(rs.getString("Username") + ":" + rs.getString("Email"));
            }
        }

        // Handle any errors that may have occurred.
        catch (Exception e) {
            e.printStackTrace();
        }

        finally {
            if (rs != null) try { rs.close(); } catch(Exception e) {}
            if (stmt != null) try { stmt.close(); } catch(Exception e) {}
            if (con != null) try { con.close(); } catch(Exception e) {}
        }
    }

}

编译:很好"%JAVA_HOME%"/bin/javac.exe -cp ./* DB.java

跑:"%JAVA_HOME%"\bin\java.exe -cp ./ DB

当我运行它时出错,不管-cp我给它什么。如果我评论 Class.forName 然后我得到一个通用的“找不到合适的驱动程序”:

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:264)
        at DB.main(DB.java:19)

标签: javasql-serverjdbcdriver

解决方案


编译代码的正确方法是:

javac -cp .;mssql-jdbc-6.4.0.jre8.jar DB.java

运行代码的正确方法是:

java -cp .;mssql-jdbc-6.4.0.jre8.jar DB

两者都假定DB.java并且mssql-jdbc-6.4.0.jre8.jar位于当前目录中,并且您使用的是 Java 8。

您当然还需要修复连接 URL,即删除microsoft

String connectionURL = "jdbc:sqlserver://HomeServer:1433;databaseName=MY_FIRST_DB";

这一切都记录在这里:https ://docs.microsoft.com/en-us/sql/connect/jdbc/using-the-jdbc-driver?view=sql-server-2017


推荐阅读