I am trying to connect my JDBC to MySQL, but it gives me "no suitable driver found". This happens only on Windows, while on macOS it will work just fine. It gave me the same error on macOS, but I started MySQL server from MySQL preferences pane in Mac settings and made sure the password was correct in my code.
This is the main class
public class Library {
public static void main(String[] args){
final String DB_URL="jdbc:mysql://localhost";
final String USER = "root";
final String PASS = "root";
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE DATABASE Biblioteca";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
System.out.println(e);
}
ConnectionProvider connection=new ConnectionProvider(USER,PASS,"Biblioteca");
UserTable userTable=new UserTable(connection.getMySQLConnection());
userTable.createTable("Users");
AddressTable addressTable=new AddressTable(connection.getMySQLConnection());
addressTable.createTable("Address");
AdminTable adminTable=new AdminTable(connection.getMySQLConnection());
adminTable.createTable("Admin");
This is the connection class
public final class ConnectionProvider {
private final String username;
private final String password;
private final String dbName;
/**
* @param username the username used to connect to the database
* @param password the password used to connect to the database
* @param dbName the name of the database to connect to
*/
public ConnectionProvider (final String username, final String password, final String dbName) {
this.username = username;
this.password = password;
this.dbName = dbName;
}
/**
* @return a Connection with the database specified in the class constructor
* @throws IllegalStateException if the connection could not be establish
*/
public Connection getMySQLConnection() {
final String dbUri = "jdbc:mysql://127.0.0.1/"+dbName;
try {
// Thanks to the JDBC DriverManager we can get a connection to the database
return DriverManager.getConnection(dbUri, this.username, this.password);
} catch (final SQLException e) {
throw new IllegalStateException("Could not establish a connection with db", e);
}
}
}