I understand that this could be something very basic but I am not sure what exactly am I missing here.
I am trying to load a properties file and trying to establish a connection to MySQL but I am encountering java.sql.SQLException
database.jdbc.url = jdbc:mysql://localhost:3306/foo
database.jdbc.driver = "com.mysql.jdbc.Driver"
database.jdbc.username = "java"
database.jdbc.password = "whatever"
private static final String PROPERTIES_FILE = "MyDatabaseProperties.properties";
private static final Properties PROPERTIES = new Properties();
private static final String PROPERTY_URL = "database.jdbc.url";
//private static final String PROPERTY_DRIVER = "database.jdbc.driver";
private static final String PROPERTY_USERNAME = "database.jdbc.username";
private static final String PROPERTY_PASSWORD = "database.jdbc.password";
static {
try {
PROPERTIES.load(new FileInputStream(PROPERTIES_FILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns a connection to the database.
*
* @return A connection to the database.
* @throws SQLException If acquiring the connection fails.
*/
public Connection getConnection() throws SQLException {
if (connection == null) {
// 1.
connection = DriverManager.getConnection(PROPERTIES.getProperty(PROPERTY_URL),
PROPERTIES.getProperty(PROPERTY_USERNAME), PROPERTIES.getProperty(PROPERTY_PASSWORD)); // THROWS EXCEPTION
// 2.
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/foo", "java", "whatever"); // CONNECTS FINE
}
System.out.println("Connected!");
return connection;
}
When I am hard-coding the url,username and password, connection is established without any issues but PROPERTIES.getProperty throws exception.
java.sql.SQLException: Access denied for user '"java"'@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at core.DatabaseLoader.getConnection(DatabaseLoader.java:74)
at app.AppMain.main(AppMain.java:22)
Property file syntax does not require quotes, if add them they become part of the property value. Use
database.jdbc.driver = com.mysql.jdbc.Driver
database.jdbc.username = java
database.jdbc.password = whatever