Search code examples
mysqljdbcxamppconnector

I am working with JDBC, and I have used mysql-connector 8 to run my java program from command line


When I am compiling the Java code, I have written the command line shows the following:

 C:\HTML>javac Jdbc.java 
    Jdbc.java:5: error: package com.mysql does not exist
    Class.forName(com.mysql.jdbc.Driver);
                           ^
    1 error

I have installed XAMPP and started the Apache, MySQL and Tomcat and they are working. I have installed MySQL Connector which is platform independent and latest. I have copied the JAR executable file to the JDK folder. I have added the jar executable file path in the edit system environment variables, ''' Class.forName(com.mysql.jdbc.Driver);'''


Solution

  • If you reference classes from a library, you should add that library to the classpath (i.e. javac -cp .;path\to\your\mysql-connector.jar Jdbc.java). However, that would immediately result in a different error, because that code should be Class.forName("com.mysql.jdbc.Driver") (passing a String).

    Some further remarks:

    I have copied the JAR executable file to the JDK folder.

    You should never manually copy files to the JDK folder (in older versions there was the ext mechanism, but this no longer exists in recent Java versions). In addition, MySQL Connector/J is a library, not an executable jar.

    I have added the jar executable file path in the edit system environment variables

    Java JARs do not belong on the PATH. In theory you can add them to CLASSPATH environment variable, but that is generally considered a bad idea: most ways of executing Java do not actually use it, and if it does get used, it can result in unexpected behaviour because of conflicting or unexpected libraries on the classpath, etc.