I'm trying to connect to a database on localhost. Mysql is running and the database name is employees. I confirmed that the port, username, and password are correct.
The java, class, and jar file are in the same folder. I tried adding the jar file to my CLASSPATH in the system environment variables and I tried adding it using -cp like below.
javac -cp . relearnjdbc.java
javac -cp ./mysql-connector-java-8.0.20.jar relearnjdbc.java
javac -cp *.jar relearnjdbc.java
I also tried separating the files into their own folders src, class, and bin.
javac -cp ../bin -d ../class relearnjdbc.java
This is my code
public class relearnjdbc {
public static String url = "jdbc:mysql://localhost:3306/employees";
public static String username = "root";
public static String password = "root";
public static void main(String[] args){
System.out.println("Connecting to DB...");
try{
//Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection connection = DriverManager.getConnection(url, username, password);
DriverManager.getConnection(url, username, password);
System.out.println("Connected!");
}catch (Exception e){
throw new IllegalStateException("cannot connect to DB ", e);
}
}
}
These give java.lang.ClassNotFoundException. I know its deprecated, but it was in a lot of answers to similar questions.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Class.forName("com.mysql.jdbc.Driver");
I'm not using an IDE, tomcat, netbeans, apache, phpadmin, or anything else. As far as I can tell a lot of other people that have asked this question were using one of these or they didn't have the jar file in their classpath.