gpt4 book ai didi

java - 如何在 Java 中将属性传递给 MySQL 语句拦截器?

转载 作者:行者123 更新时间:2023-11-29 10:17:37 27 4
gpt4 key购买 nike

我正在制作一个自定义 MySQL StatementInterceptorV2,并且希望向其传递一些自定义属性(例如一些任意 String)。考虑到语句拦截器是这样创建的(根据 https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html ):

public Connection getDatabaseConnection(String jdbcUrl, String dbUser, String dbPassword) throws SQLException
{
Properties dbProps = new Properties();

dbProps.put("statementInterceptors", "package.path.to.ConnectionInterceptor");
dbProps.put("user", dbUser);
dbProps.put("password", dbPassword);

return DriverManager.getConnection(jdbcUrl, dbProps);
}

如何向其传递值?显然我没有调用构造函数或任何东西,这将是执行此类操作的正常方法。这是我的语句拦截器,如果有帮助的话。

public class ConnectionInterceptor implements StatementInterceptorV2
{
@Override
public void init(Connection conn, Properties props) throws SQLException {

}

@Override
public ResultSetInternalMethods preProcess(String sql,
Statement interceptedStatement,
Connection connection) throws SQLException {

Subsegment subsegment = AWSXRay.beginSubsegment(connection.getHost());

subsegment.putSql("url", connection.getHost());
String user = connection.getProperties().getProperty("user");
if(user != null) {
subsegment.putSql("user", user);
}
subsegment.putSql("database_type", connection.getMetaData().getDatabaseProductName());
subsegment.putSql("database_version", connection.getMetaData().getDatabaseProductVersion());
subsegment.putSql("driver_version", connection.getMetaData().getDriverVersion());

String finalSql = sql;
// SQL is null in a prepared statement, so we have to grab the SQL from the statement itself
if(interceptedStatement instanceof PreparedStatement) {
finalSql = ((PreparedStatement) interceptedStatement).getPreparedSql();
}
subsegment.putSql("sanitized_query", finalSql);
subsegment.setNamespace(Namespace.REMOTE.toString());

// Return null to return ResultSet as is, without modification
return null;
}

@Override
public boolean executeTopLevelOnly() {
return false;
}

@Override
public void destroy() {

}

@Override
public ResultSetInternalMethods postProcess(String sql,
Statement interceptedStatement,
ResultSetInternalMethods originalResultSet,
Connection connection,
int warningCount,
boolean noIndexUsed,
boolean noGoodIndexUsed,
SQLException statementException) throws SQLException {
AWSXRay.endSubsegment();

// Return null to return ResultSet as is, without modification
return null;
}
}

通过 Properties 对象传递自定义属性是执行此操作的唯一方法吗?

最佳答案

您可以创建一个名为 ConnectionInterceptorParameters 的新类,它具有静态线程本地参数。您可以在进行 sql 调用之前在业务逻辑中填充本地线程,并且拦截器可以使用这些值。然后,您必须在调用完成后清除线程本地。

关于java - 如何在 Java 中将属性传递给 MySQL 语句拦截器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49881296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com