-2

I'm going crazy and none of the pre-existing solutions seem to work for me. I'm old-school, so just coding in NotePad++/EditPlus and compiling via CLI. I've got a super generic DB.JAVA file and I can't get passed the attempt to load the SQL Driver Class. I'm at a loss and hoping others can help. Long term, this will become used in a JSP on Tomcat.

Java Version: Either 1.8.0_181 or 10.0.2 (I have both, x64 builds)

SQL Server: 2017 Express

JDBC JAR: mssql-jdbc-6.4.0.jre8.jar (presently in the same dir as DB.java)

My basic code:

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) {}
        }
    }

}

Compiles: fine with "%JAVA_HOME%"/bin/javac.exe -cp ./* DB.java

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

Error when I run it, no matter what -cp I give it. If I comment the Class.forName then I get a generic "no suitable driver found":

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)
Gord Thompson
  • 98,607
  • 26
  • 164
  • 342
Michael Lowden
  • 83
  • 1
  • 10
  • `javac` is for compiling, the options passed here make no difference to how you are running it. **So**, how are you running it? Do you pass in the values for the `classpath`? – Scary Wombat Jul 26 '18 at 04:15
  • As per the [javadocs](https://docs.oracle.com/javase/8/docs/technotes/tools/windows/classpath.html) try setting in this format `java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool` – Scary Wombat Jul 26 '18 at 04:25
  • C:\_TEMP\JAVA\sqljdbc samples\resultsets>"%JAVA8_HOME%"\bin\java.exe -cp "C:\_TEMP\JAVA\sqljdbc samples\resultsets\mssql-jdbc-6.4.0.jre8.jar" DB ============ Error: Could not find or load main class DB – Michael Lowden Jul 26 '18 at 04:30
  • 2
    Looks like you still need to add `./` to your classpath, **but** seriously, why don't you safe yourself heaps of pain and download a free IDE like eclipse? – Scary Wombat Jul 26 '18 at 04:34
  • Mostly because it's too bloated. I have the same issue with Visual Studio. I don't want to wait for the app to load when I can write the Java by hand for something tiny like this. Secondarily. I tried it ~10 years ago and gave up on it due to bloat. But maybe, since I'm back 'playing' with Java I'll try again. And I'm sure there are plenty of little self-training-how-to things that'll resolve my pains with it way back when. – Michael Lowden Jul 26 '18 at 04:39
  • 3
    @MichaelLowden The time an IDE needs to load is pretty neglectable compared to the time it can save by helping identifying errors and showing where and why they occur. – Modus Tollens Jul 26 '18 at 04:49
  • @MichaelLowden: Keep the sqljdbc4.jar in folder - C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\ and then in CLI run the command: set classpath=C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\sqljdbc4.jar;.; – Gaurav Jul 26 '18 at 05:33
  • 1
    @Gaurav That is extremely bad advice. The `lib/ext` folder was never intended for that use, it is deprecated and has been removed in newer Java versions. – Mark Rotteveel Jul 26 '18 at 08:56
  • @MarkRotteveel Yes my suggested advice is not good & unfortunately I was also not aware of whether it has been removed from Java 9 & 10 release. – Gaurav Jul 26 '18 at 10:08
  • lib/ext was one of my first gotos, and modern java just screams at you for it. The footer doesn't exist and there's a check now to see if you created it. – Michael Lowden Jul 26 '18 at 11:47

1 Answers1

1

Correct way to compile code is:

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

Correct way to run code is:

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

Both assumes that DB.java and mssql-jdbc-6.4.0.jre8.jar are in the current directory, and that you're using Java 8.

You will of course also need to fix the connection URL, i.e. remove microsoft:

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

This is all documented here: https://docs.microsoft.com/en-us/sql/connect/jdbc/using-the-jdbc-driver?view=sql-server-2017

Andreas
  • 138,167
  • 8
  • 112
  • 195
  • Oops. the :microsoft: was in there from some other testing and I just forgot to purge it. So ... adding .; to the beginning hurdled the classNotFoundException, though I'm not getting data now but that's a different thing I'm sure. As for adding the .; so it's like .;xyz.jar . I understood the -cp to be a semi-colon separated list and simply supplying ./* should've done it, in my mind. Anyway. It seems to be one-step further. Appreciated (and yes I've read all those materials repeatedly, but didn't think the first element of "." was important for java -vs- unimportant for javac). – Michael Lowden Jul 26 '18 at 12:16
  • FYI : using Eclipse Photon now to try to learn it. Also following a guide on "my first servlet" kind of thing that shows you how to run Tomcat from within. This is working on all the latest : Java10 / Tomcat9 for me today too. http://www.vogella.com/tutorials/EclipseWTP/article.html – Michael Lowden Jul 27 '18 at 02:14