I'm looking for a way to get the password from a java.sql.Connection object. I know there's a getUserName() method in the DatabaseMetaData object, but unfortunately no corresponding getPassword() method. Using the debugger in Netbeans I can see a field for the password, so there must be a way to get this information using reflection, but thus far I've been unable to figure out how.
-
1This will be interesting. I don't think that's possible through the public API, as you well pointed out. Perhaps somewhere in the Driver implementation or the DriverManager, if it is open source, you can find out. I doubt it is in the connection.Edwin Dalorzo– Edwin Dalorzo2011-04-12 00:31:49 +00:00Commented Apr 12, 2011 at 0:31
-
2This is one of the most bizarre requirements I ever seen. Besides, it has a potential for security breach.Vladimir Dyuzhev– Vladimir Dyuzhev2011-04-12 01:43:46 +00:00Commented Apr 12, 2011 at 1:43
-
2so, if you've seen the field in the debugger, why can't you get it using reflection?jtahlborn– jtahlborn2011-04-12 03:08:55 +00:00Commented Apr 12, 2011 at 3:08
-
1java.sql.Connection is an interface, and does not have a "field for the password", or any other (non static) fields.Paul Hanbury– Paul Hanbury2011-04-12 04:03:00 +00:00Commented Apr 12, 2011 at 4:03
-
1@Gillman I think we all should have started with this question: why in the world you do not know the password of the connections that you are using?Edwin Dalorzo– Edwin Dalorzo2011-04-12 18:03:44 +00:00Commented Apr 12, 2011 at 18:03
3 Answers
As I commented, the only way must be looking into the code. For instance, for MySQL using the latest driver (5.1.15). You can get the password like this:
public static void main(String[] args) throws Exception{
ConnectionImpl con = (ConnectionImpl) DriverManager.getConnection("jdbc:mysql://localhost:3908/mydb?user=edalorzo&password=mandrake");
System.out.println(con.getProperties().get("password"));
con.close();
}
But for this, you would need to know the class hierarchy and its implementation details.
Other databases most probably will be different. If your database is open source, like MySQL you can know the details of the inner construction and find ways to retrieve the password.
2 Comments
con.getClientInfo().getProperty("password")It is up to the implementer of the JDBC to provide that since the user and password are being passed in as a Map to the Driver.
One way to know what the Password is, is to extend the driver and include that.
class CustomDriver extends ImplementerDriver {
@Override
public Connection connect(String url, Properties info) throws SQLException {
super.connect(url, info);
// Extract password from info.
}
public String getPassword() {
....
}
}