1

When I run code that uses a sql driver for jbdc it works on eclipse. This is after I went into the project properties and added the external jar. However when I run the following from the command line it fails.

java -version
java version "1.8.0_25"
javac sql_stuff.java 
java sql_stuff -classpath conn.jar

java.sql.SQLException: No suitable driver found for jdbc:mysql://...

Same with -cp

 javac sql_stuff.java 
 java  sql_stuff -cp conn.jar 

In Eclipse all I had to do is go project > Properties > Java Build Path > Libraries and add the jar file.

Edit

Got it finally running with

java -cp .:conn.jar sqlstuff

Java seems to need to 're-add' a class path (even though it was '.' !!!) otherwise it wouldn't find the class. Also you have to use : as a separator (or sometimes ; ), god knows why. Hopefully this will help others when they stumble across issues.

4
  • 2
    You need to give the -cp on the java command, not the javac command. The driver is not needed during compilation, but it is needed at run-time. Commented Nov 13, 2015 at 21:17
  • @Andreas I updated the code, still same problem. Commented Nov 13, 2015 at 21:31
  • 1
    Put the -cp and its argument before the class name. By the way, class names should not have underscores, and should start with a capital letter, like SqlStuff. Commented Nov 13, 2015 at 21:32
  • @RealSkeptic that was it! I'll accept your answer if you post it. Commented Nov 13, 2015 at 21:34

1 Answer 1

2

When you run the java command, all the "switches" (things starting with -) that come before the class name are considered arguments to the JVM. All those that come after the class name are considered arguments to the main method in the class.

So the command line:

java ClassName -cp conn.jar

Will be interpreted as "run with no JVM arguments, passing the array { "-cp", "conn.jar" } as args to main.

While the command line:

java -cp conn.jar ClassName

Will be interpreted as "run with a classpath of conn.jar, and call main in ClassName with an empty args array".

So always remember to pass all JVM arguments, including the classpath, before the name of the class.

Sign up to request clarification or add additional context in comments.

1 Comment

I had to also pass '.' to the class path as well. Otherwise the class wouldn't be found. Thanks for the help and the detailed run down.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.