Wednesday 19 July 2017

how to avoid java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

                  Hi, in this post we will see how to avoid exception java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.

                  If you are running jdbc program on terminal in Linux; you may get following error:







e.g.
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac jdbc.java
parag@parag-Inspiron-N4010:~/Desktop/prog$ java jdbc
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:195)

at jdbc.main(jdbc.java:7)


                           To avoid above error, we have to add mysql jar file. To do this, follow the following step: 


                     We have to download mysql-connector.jar file. We can download it from the link http://www.java2s.com/Code/Jar/m/Downloadmysqlconnectorjar.htm. Extract zip file and save it at location /usr/share/java.              

                     To run jdbc program on terminal in Linux, you need to edit .bashrc file. You will get .bashrc file in following location

/home/[user name]/.bashrc

e.g. 

parag@parag-Inspiron-N4010:~$ gedit /home/parag/.bashrc


Then add following line in .bashrc file:

export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector.jar


Save it and restart the system.

                   Rerun the jdbc code, you will not get error again.


                   

No comments:

Post a Comment