我需要使用 Connection 对象获取 JDBC 连接 id(UUID)。有什么方法可以获取连接ID吗?
好吧,如果您指的是“sql-connection to sql-server”,那么 jdbc 没有这方面的标准工具。这是 jdbc:mysql 的手工示例(注意 - 反射和限制字符):
private long getJdbcConnectionId(Connection conn) {
long cid = 0;
try {
Field f_conn__conn = conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn.setAccessible(true);
Object o_conn__conn = f_conn__conn.get(conn);
Field f_conn__conn__conn = o_conn__conn.getClass().getSuperclass().getDeclaredField("_conn");
f_conn__conn__conn.setAccessible(true);
Object o_conn__conn__conn = f_conn__conn__conn.get(o_conn__conn);
Field f_connectionId = o_conn__conn__conn.getClass().getSuperclass().getDeclaredField("connectionId");
f_connectionId.setAccessible(true);
cid = f_connectionId.getLong(o_conn__conn__conn);
f_connectionId.setAccessible(false);
f_conn__conn__conn.setAccessible(false);
f_conn__conn.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
return cid;
}
编辑:
这样可以避免编译时耦合,使用反射
import java.sql.Connection;
import java.sql.DriverManager;
...
public String getMysqlConnectionId()
{
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
Class<?> clazz = Class.forName("com.mysql.jdbc.MySQLConnection");
Object o = connection.unwrap(clazz);
return (String) clazz.getMethod("getId").invoke(o).toString();
} catch ( Exception e ) {
return e.getMessage();
}
}
通过将
java.sql.Connection
对象投射到 com.mysql.jdbc.MySQLConnection
并使用 getId()
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.MySQLConnection;
...
public long getMysqlConnectionId()
{
Connection connection = DriverManager.getConnection("jdbc:mysql://host:3306/schema", "myuser", "mypassword");
// would throw a ClassCastException in case this is not a mysql one, of course
return ((MySQLConnection) connection).getId();
}
但这有点可怕的耦合你的项目在编译时与 MySQL
注意:当我对此投反对票时,我不会感到被冒犯,这是应得的;-)
<!-- pom.xml -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>x.y.z</version>
</dependency>
其他一些人显然正在使用
connection.unwrap(com.mysql.jdbc.MySQLConnection)
,这可能感觉更合适一点,但并没有消除与 com.mysql
的编译时耦合
https://github.com/prestodb/presto/issues/9425
这是我如何获取 Oracle SID 的示例:
public int getConnectionSid() {
try {
if (connection == null || connection.isClosed())
return -1;
if (connectionSid == -1) {
try {
Method method = connection.getClass().getDeclaredMethod("getSessionId", null);
method.setAccessible(true);
connectionSid = (Integer)method.invoke(nativeConnection, null);
method.setAccessible(false);
} catch (NoSuchMethodException e) {
return -1;
} catch (IllegalAccessException e) {
return -1;
} catch (InvocationTargetException e) {
return -1;
}
}
return connectionSid;
} catch (SQLException e) {
return -1;
}