javamysqljdbcvisual-studio-codeconnection

JDBC with VSCode class not found


I am having serious trouble creating a Java Project with VS Code with adding the "mysql-connector-java-8.0.21.jar". I have done the following steps:

I tried using both jdk 11 and 15 (not 8 since VS Code doesn't support it anymore)

Launching my code result in the error: java.lang.ClassNotFoundException: com.mysql.cj.LocalizedErrorMessages

Here is an extract of my code:

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SimpleJDBCApplication {

   static final String DB_URL = "jdbc:mysql://localhost:3306/company";
   static final String DB_DRV = "com.mysql.jdbc.Driver";
   static final String DB_USER = "root";
   static final String DB_PASSWD = "";

   public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
         IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

      Connection connection = null;
      Statement statement = null;
      ResultSet resultSet = null;

      try{
          /*To connect with a database using JDBC you need to select get the
                 driver for the respective database and register the driver.
                 The forName() method of the class named Class accepts a class name
                as a String parameter and loads it into the memory, Soon the is
                loaded into the memory it gets registered automatically  */  
                //Take new instance
         System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
         Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
         connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);
         statement=connection.createStatement();
         resultSet=statement.executeQuery ("SELECT * FROM dept");
         while(resultSet.next()){
            System.out.printf("%d\t%s\t%s\n",
            resultSet.getInt(1),
            resultSet.getString(2),
            resultSet.getString(3));

The error occures at the line connection=DriverManager.getConnection(DB_URL,DB_USER,DB_PASSWD);

Thank you for any help

Library added Error


Solution

  • 1.This is applicable to MySQL version below 8.0:

    static final String DB_URL = "jdbc:mysql://localhost:3306/company";

    Change it to

    static final String DB_URL ="jdbc:mysql://localhost:3306/company?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
    

    2.Transfer com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver;

    3.Class.forName("com.mysql.cj.jdbc.Driver") is enough, also with this code, System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver") isn't needed, you can comment or delete it;

    This works for me and you can have a try.