Reputation: 11
I am trying to connect to MySQL using JDBC. I have one strange behavior if I passed the hardcode value for url, username and password to DriverManager.getConnection() the connection to database is OK. But if I passed argument as variable the connection to JDBC failed with below Error.
java.sql.SQLException: No suitable driver found for "jdbc:mysql://localhost:3306/hplus"
FileInputStream fis = new FileInputStream(path+"config.properties");
Properties prop = new Properties();
prop.load(fis);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
conn=DriverManager.getConnection(url, username, password);
//conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/hplus","root","123Nbr@");;
}catch(Exception e) {
System.out.println(e);
}
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
"jdbc:mysql://localhost:3306/hplus"
"root"
"123Nbr@"
java.sql.SQLException: No suitable driver found for "jdbc:mysql://localhost:3306/hplus"
Upvotes: 1
Views: 1514
Reputation: 65054
I think you haven't quite got the syntax of .properties
files right.
You haven't included your properties file in your question, but I'm guessing your properties file looks like the following:
url="jdbc:mysql://localhost:3306/hplus"
username="root"
password="123Nbr@"
The problem is the quotes. They shouldn't be there. The quotes don't get removed when the properties file is read, they end up in your URL, username and password. The presence of these quotes is also clear from your output.
Because of these quotes you are basically running this:
conn=DriverManager.getConnection("\"jdbc:mysql://localhost:3306/hplus\"","\"root\"","\"123Nbr@\"");
If you want, you can verify that this line gives the exact same error message as in your question.
The fix is to remove the quotes from your properties file:
url=jdbc:mysql://localhost:3306/hplus
username=root
password=123Nbr@
Upvotes: 1