How to get UserName from java.sql.Connection?

I have a data source for SQLServer created in Weblogic with the username 'sa'.

In the code, I use the following to get the username.

Context ctx = new InitialContext(prop);
Object obj = ctx.lookup("sqlserver1");
System.out.println("Data Source Found….");
DataSource ds = (DataSource) obj;
Connection conn = ds.getConnection();
DatabaseMetaData mtdt = conn.getMetaData();
// Get UserName
System.out.println("User name: " + mtdt.getUserName());

But the above code always returns "dbo" as the username. I expected the username to be "sa". If DB is Oracle, it works great. Is there a general way for me to get a username for all different types of databases.

+5
source share
2 answers

DatabaseMetaData.getUserName(), , , . JDBC escape USER() (, SELECT {fn USER()} FROM DUAL), JDBC, , , DatabaseMetaData. SQL CURRENT_USER ( USER) , : 1) (, DUAL Oracle, t) 2) SQL, CURRENT_USER USER .

DataSource, USER ( 9.1 JDBC 4.1, , , ).

, :

Method getter = new PropertyDescriptor("user", ds.getClass()).getReadMethod();
String value = (String) getter.invoke(ds);

, 1) DataSource ds getUser() 2), (, SQL Server ).

+4

FWIW, Java 1.7 Connection.getSchema(). , 1,7, -, .

0

All Articles