1

I have tried to connect with the mysql database by the JDBC. But I am no able to connect it with the vs code.I just have a question that we need the mavan project to connect with db always. I have also add the code please Refer and suggest me how can i connect with the db. Thanks!

The error that i have got while connecting. enter image description here

package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;

public class createDb {
    // JDBC and database properties.
    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DB_URL = "jdbc:mysql://localhost:3306/";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "root";
    
public static void main(String args[]) {
        Connection conn = null;
        try {
            // Register the JDBC driver
            Class.forName(DB_DRIVER);
            // Open the connection
            conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
            if (conn != null) {
                System.out.println("Successfully connected.");
            } else {
                System.out.println("Failed to connect.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • Did you include the driver's library in your project? Is this a Maven or Gradle project you have there? – akarnokd Jun 21 '22 at 12:59
  • Please never post images of text. They are not searchable, we cannot copy-paste... Always copy-paste the text and format it properly. Your classpath is wrong (no driver jar). I can't show you what it should be because you have made it impossible to copy and paste – g00se Jun 21 '22 at 13:18
  • java.lang.ClassNotFoundException: com.mysql.jdbc.Driver I thinks you are talking about the above error,right – Vaibhav Pawar Jun 21 '22 at 13:32
  • it just a simple java project,that I have wrote in vs code. so we need the mavan project to connect with the database. – Vaibhav Pawar Jun 21 '22 at 13:34
  • You don't have the MySQL Connector/J driver on your classpath. – Mark Rotteveel Jun 21 '22 at 16:58
  • This same code is working in the eclipse under the maven project.But not in the vs code.Main question of mine is that we always need the maven project like setup to connect with the db – Vaibhav Pawar Jun 21 '22 at 17:33
  • 1
    No, you don't always need Maven, but if you don't use things like Maven or Gradle, you need to manually add the necessary dependencies like MySQL Connector/J to your project. – Mark Rotteveel Jun 22 '22 at 07:42
  • So how can we add the dependencies in the vs code for the specific program like above – Vaibhav Pawar Jun 22 '22 at 11:45
  • hey, my issue is fixed i have add the jar file by extracting it and put it in the lib folder and now i am able to connect with the database through my vs code. Thanks! – Vaibhav Pawar Jun 22 '22 at 15:42

0 Answers0