Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in vscode. have added referenced libraries jar file, error persists

Viewed 71

Here is a little insight, I have reinstalled VS Code and its extensions, used this code without any extensions, and the error remains the same.

I also added the jar file in referenced libraries and refreshed it, but the code doesn't work.

I tried importing com.mysql.jdbc.Driver and com.mysql.cj.jdbc.Driver, tried changing com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver.

This code works in eclipse IDE, but I would rather not switch my entire operation to eclipse.

import java.sql.*;

public class newapp2jdbc {
    public static void main(String[] args) throws Exception {
        

    String url = "jdbc:mysql://localhost:3306/sql_workbench";
    String uname = "root";
    String pass = "0768";
    String query = "select name from student where id=3";

    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, uname, pass);
    Statement st = con.createStatement();

    ResultSet rs = st.executeQuery(query);

    rs.next();
       
    String name = rs.getString(1);
    System.out.println(name);
    st.close();
    con.close();
    }
}
1 Answers

First try to use the command Java:Clean Language Server Workspace in the command palette to see if the problem can be solved.

enter image description here

If the problem persists, follow the steps below to create a new project.

  1. Ctrl+Shift+P to open the command palette, search for and select Java:Create Java Project...

    enter image description here

  2. Then Select No Build tools --> select a folder --> type the project name (Screenshot of steps)

  3. Now that you have a new Java project, in the JAVA PROJECTS panel click the plus sign after src to create a new class

    enter image description here

  4. Type the class name (newapp2jdbc) and hit Enter

    enter image description here

  5. Paste the code from your question in the generated newapp2jdbc.java file

  6. Click the plus sign to the right of Referenced Libraries to add dependencies

    enter image description here

    Here is mysql-connector-java-8.0.30.jar for me, you can download it from the MySQL official website.

  7. The code can now be run.

    enter image description here

Note: The full Extension Pack for Java needs to be installed

Related