简体   繁体   中英

java.lang.ClassNotFoundException: com.sqlserver.jdbc.Driver

I'm trying to connect with MS SQL Server using a Java Application. This is the code I'm using:

public static void main(String[] args)  {
    try {  
        Class.forName("com.sqlserver.jdbc.Driver");                                   
        Connection con=DriverManager.getConnection("jdbc:sqlserver:<SERVER>","user","password");  
        Statement stmt = con.createStatement();  
        ResultSet rs = stmt.executeQuery("SELECT TOP 1 [MsgTextArabic] FROM 
     [FactBulkSMS].[dbo].[Messages] order by SendingDateTime desc");

        while(rs.next())  
            System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
    }
    catch(Exception e) { 
        System.out.println(e);
        e.printStackTrace();
    }

When running this code, the following Exception is thrown:

java.lang.ClassNotFoundException: com.sqlserver.jdbc.Driver

java.lang.ClassNotFoundException: com.sqlserver.jdbc.Driver
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at test.main(test.java:13)

The Exception is complaining, that Class.forName("com.sqlserver.jdbc.Driver"); is unable to find the JDBC driver.

According to the Docs, you need to add the path where you put the driver into the ClassPath Variable. From Eclipse this can be done by importing the .jar files into the project and referencing them.

Source and further information: https://docs.microsoft.com/en-US/sql/connect/jdbc/using-the-jdbc-driver

It seems that the JVM can not find the class com.sqlserver.jdbc.Driver , this is most likely because the JAR has not been included in your project's classpath.

Since you are using eclipse I would recommend adding the JAR via Eclipse's "build path".

Start by checking which is the correct JAR for your set-up from the Microsoft docs HERE You can then download the JAR from the Maven repo

Then inside Eclipse, Right click your project >> Build Path >> Configure Build Path. Select the Libraries tab, then on the right column click on, "Add External JARs"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM