Brian Brian - 1 year ago 146
Java Question


I'm setting up a simple JDBC connection to my working MySQL database on my server. I'm using the Connector-J provided by MySQL. According to their documentation, I'm suppose to create the CLASSPATH variable to point to the directory where the mysql-connector-java-5.0.8-bin.jar is located. I used

export set CLASSPATH=/path/mysql-connector-java-5.0.8-bin.jar:$CLASSPATH
. When I type
to see if it exists, everything seems fine. But then when I open a new terminal and type
it's no longer there. I think this is the main reason why my Java server won't connect to the JDBC, because it isn't saving the CLASSPATH variable I set.

Anyone got suggestions or fixes on how to set up JDBC in the first place?

Answer Source

Forget the CLASSPATH environment variable. It's a big joke. It's ignored by pretty much everything else than a low-level java com.example.Foo command. It's ignored when you add the -jar argument. It's ignored when you add the -cp or -classpath argument. It's ignored by IDE's and web/application servers. That environment variable was intented as a convenience for starters. But beyond that, it's useless.

It boils down to that the JAR file has got to be placed in any of the existing/default paths of the runtime classpath of the Java application in question, or that at least the path to the JAR file is to be added to the runtime classpath of the Java application in question.

Since you're talking about a server and considering the fact that the CLASSPATH environment variable doesn't work, I'll assume that it's actually a webserver/appserver such as Apache Tomcat. If that's indeed true, you've got to either drop the JAR file in Tomcat/lib folder (if you use the container managed DataSource approach for a fast connection pool), or in webapp's WEB-INF/lib folder (if you use the poor man's Class#forName() approach to load the driver).

If it's not and it's actually a Java application which is to be executed as a JAR, then you've got to specify the classpath in MANIFEST.MF file of the JAR in question. But if it's also not that and it is a loose .class file, then you've got to specify the classpath in -cp or -classpath argument of java command. To save yourself from typing it again and again when executing it, just create a .sh file with the command.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download