Reputation: 3155
I have currently run into a problem with special chars like :
in the URL for a JDBC MySQL connection. Since it is an URL I thought I could just URL encode the strings I supply (for like the password). However it is not working.
I tried the following code
public class DatabaseConnection {
protected static String urlEncode(String toEncode) {
try {
return URLEncoder.encode(toEncode, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Won't happen anyways!
e.printStackTrace();
return null;
}
}
public DatabaseConnection(String host, int port, String database, String user, String password)
throws SQLException {
StringBuilder connectionURL = new StringBuilder();
connectionURL.append("jdbc:mysql://").append(urlEncode(host)).append(':').append(port).append('/')
.append(urlEncode(database)).append("?user=").append(urlEncode(user)).append("&password=")
.append(urlEncode(password));
connect(connectionURL);
}
}
(The connect method works well. It is dependend on the library I use so supplying the code won't do much.)
The code works well as long as password (Or any other string) doesn't contain :
. It could be that other chars don't work either but I haven't tested that yet. The :
gets escaped to %3A
. And then the login fails. I verified several times that the password is correct. (Tested it by connection to the MySQL server over the command line)
Upvotes: 1
Views: 1570
Reputation: 108932
JDBC urls do not necessarily follow the rules for 'normal' internet URLs. However, looking at the code in MySQL Connector/J NonRegisteringDriver.parseURL
, it applies java.net.URLDecoder
to the keys and values, so I would actually expect this to work; not sure what is going on.
If the specific problem is with the username and password, then the solution is to not include them in the URL, but use one of the following:
javax.sql.DataSource
implementation that is configured with the right propertiesDriverManager.getConnection(String url, String user, String password)
DriverManager.getConnection(String url, Properties info)
and pass the username and password as properties user
and password
in the Properties
object (you can do the same for other properties)If you can't call these because of the API you use, you might want to contact the library author to see what can be done to fix it.
And finally there is also a pragmatic solution: just don't use a colon in your password.
As a sidenote: using StringBuilder
like you do is not necessary here; the Java compiler will optimize this for you if you'd use plain string concatenation.
Upvotes: 3