BrainStone
BrainStone

Reputation: 3155

Issues with JDBC MySQL URLs and special chars

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

Answers (1)

Mark Rotteveel
Mark Rotteveel

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:

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

Related Questions