0

I'm trying to set up JDBC to establish a connection to a MySQL database from my Linux machine (specifically KDE side-loaded on a Chromebook). I've seen some posts suggesting one sets the CLASSPATH variable in /etc/bash.bashrc, some say /etc/profile. Which of these is the standard?

If I manually set my classpath through a bash command:

export CLASSPATH=/home/username/JDK/mysql-connector-java-8.0.15.jar

It will compile just fine, but running the program yields Error: Could not find or load main class myTest. Alternatively, if I use the default classpath, compile, and run, I get a ClassNotFoundException for anything in the code that uses JDBC content.

Ian Gradert
  • 150
  • 1
  • 7
  • 3
    you should add the directory (or JAR file) where to find your class to the class path too: e.g. `CLASSPATH=.;/home/username/...` or `CLASSPATH=/home/username/my.jar;/home/username/...` (if no CLASSPATH is set, the default is the current directory `.`) – user85421 Mar 01 '19 at 21:52
  • Those just starting out (myself included, back then) often struggle before they hit upon the `CLASSPATH=.;/and/so/on` "trick". – Gord Thompson Mar 01 '19 at 22:44
  • Possible duplicate of [What is a classpath?](https://stackoverflow.com/q/2396493/608639), [How to set the classpath in Java?](https://stackoverflow.com/q/5172507/608639), [How to set Java classpath in Linux?](https://stackoverflow.com/q/2973624/608639), etc. – jww Mar 01 '19 at 23:28
  • Nearly no normal Java application uses the `CLASSPATH` environment variable because it can lead to weird behavior and bugs if a different version of a dependency gets loaded before the one the application wants. In addition applications executed with `-jar` (and I guess that is most of them) will even ignore that environment variable and only use the classpath specified in its manifest. It is better to forget about the existence of the `CLASSPATH` environment variable.. – Mark Rotteveel Mar 02 '19 at 07:07

1 Answers1

1

Classpath should include all classes that JVM needs to run your application: all dependencies and your application classes.

You can pass classpath for each java invocation like

java -jar <jar file>

or

java -cp <your full classpath goes here> <your main class>

But you can also use build tools to either build fat jar with dependencies and configured classpath or build zip with main jar, dependencies is a separate folder and preconfigured classpath set in your jar.

Ivan
  • 8,508
  • 2
  • 19
  • 30
  • just a *note*: when using `-jar` I believe `-cp` is not used, instead the `Class-Path` in the manifest is. Based on experience and [documentation](https://docs.oracle.com/en/java/javase/11/tools/java.html#GUID-3B1CE181-CD30-4178-9602-230B800D4FAE): *"When you use -jar, the specified JAR file is the source of all user classes, and **other class path settings are ignored**."* – user85421 Mar 01 '19 at 21:44
  • @CarlosHeuberger, thanks. Corrected my answer – Ivan Mar 01 '19 at 21:45