java.sql.SQLException:找不到合适的驱动程序(SQL Server Express)

时间:2018-07-26 04:10:04

标签: java sql-server jdbc driver

我快要疯了,以前所有的解决方案似乎都不适合我。我是老派,所以只需在NotePad ++ / EditPlus中编码并通过CLI进行编译即可。我有一个超级通用的DB.JAVA文件,无法通过尝试加载SQL Driver类的尝试。我很茫然,希望别人能帮上忙。从长远来看,它将在Tomcat上的JSP中使用。

Java版本:1.8.0_181或10.0.2(我都拥有x64构建)

SQL Server :2017 Express

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)

1 个答案:

答案 0 :(得分:1)

正确的代码编译方式是:

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

正确的代码运行方式是:

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

两者都假设DB.javamssql-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