2016-04-21 53 views
1

这是Using a JMeter JDBC connection in Java code的后续操作。如何在DataSourceElement类中使用诸如getPassword()或getUsername之类的方法?我想要从JDBC连接配置配置中获取并修改用户名和密码(等等)。在Java/beanshell代码中操纵JMeter 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 
[email protected] 

回答

1

它有可能使用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); 

但我认为你将能够得到密码这种方式会造成巨大的安全风险的能力。

顺便说一句,你可以在jmeter.log文件被周围的BeanShell的代码放到try/catch块一样获得更友好的异常消息:

try { 
    //your code here 
} 
catch (Throwable ex) { 
    log.error("Something wrong", ex); 
    throw ex; 
} 

有关更多信息,请参见How to Use BeanShell: JMeter's Favorite Built-in Component使用JMeter的和来自Beanshell测试元素的Java API