这是 Using a JMeter JDBC connection in Java code 的后续内容。如何使用 DataSourceElement 类中的 getPassword() 或 getUsername 等方法?我想从 JDBC 连接配置配置中获取然后修改用户名和密码(以及其他内容)。
我在那篇文章中使用了相同的代码,但在 beanshell 采样器中(最终将在预处理器元素中使用)。我认为问题是我需要一个 DataSourceElement 对象并且只定义了一个 Connection 对象。这就是我被困住的地方。
我的代码:
import java.sql.Connection;
import org.apache.jmeter.protocol.jdbc.config.DataSourceElement;
print("\nbeanshell script beginning");
try {
Connection con = DataSourceElement.getConnection("jdbcconfig");
print(con);
String conpasswd = con.getPassword();
print(conpasswd);
if(con!=null)
con.close();
}
catch (Throwable ex) {
log.error("Something went wrong: ", ex);
}
print("the end");
jmeter.log 返回:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.sql.Connection; import org.apache.jmeter.protocol.jdbc.config.DataSo . . . '' : Typed variable declaration : Error in method invocation: Method getPassword() not found in class'com.sun.proxy.$Proxy0'
控制台输出返回连接对象,然后在错误处停止:
beanshell script beginning
org.postgresql.jdbc4.Jdbc4Connection@7849e2a7
最佳答案
可以使用 DatabaseMetaData 获取一些连接信息类如:
import java.sql.Connection;
import org.apache.jmeter.protocol.jdbc.config.DataSourceElement;
import java.sql.DatabaseMetaData;
Connection con = DataSourceElement.getConnection("jdbcconfig");
DatabaseMetaData meta = con.getMetaData();
String conusername = meta.getUserName();
print(conusername);
但我不认为您能够通过这种方式获取密码,因为这种能力会导致巨大的安全风险。
顺便说一句,通过将 Beanshell 代码包含在 try/catch block 中,您可以在 jmeter.log 文件中获得更友好的异常消息,如下所示:
try {
//your code here
}
catch (Throwable ex) {
log.error("Something wrong", ex);
throw ex;
}
参见How to Use BeanShell: JMeter's Favorite Built-in Component有关使用 Beanshell 测试元素中的 JMeter 和 Java API 的更多信息
关于java - 在 Java/beanshell 代码中操作 JMeter JDBC 连接字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36779835/