I'm a beginner in JDBC and I want to connect to a MySQL instance on my local machine. Below is the MySQL Instance I'm trying to connect to. It exists on my local machine. It has a database called my_db2 present on it. And I want to work with it's tables.
To connect to the above database, I wrote the following code.
import java.sql.*;
public class TestMySQL {
public static void main(String[] args) {
try(
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3308/my_db2","root","B03091999b");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("Select * from department");)
{
while(rs.next()){
System.out.println(rs.getString("DeptName"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
I also added the mysql-connector library using IntelliJ.
Yet, when I try to connect to the database, I keep getting this error.
java.sql.SQLException: No suitable driver found for jdbc:mysql://127.0.0.1:3308/my_db2
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at TestMySQL.main(TestMySQL.java:7)
Even though, I've installed the mysql-connector driver using IntelliJ, I keep getting this error. I tried loading the driver explicitly too as follows:
import java.sql.*;
public class TestMySQL {
public static void main(String[] args) {
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3308/my_db2","root","B03091999b");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("Select * from department");
while(rs.next()){
System.out.println(rs.getString("DeptName"));
}
} catch (SQLException | ClassNotFoundException throwables) {
throwables.printStackTrace();
}
}
}
At this point, I started getting the following error.
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at TestMySQL.main(TestMySQL.java:10)
As per my knowledge, I followed all the steps properly, to add the mysql-connector file to the libraries. I'm not sure what's going wrong. Please do help me solve this problem. Any help would be appreciated.