2016-04-21 51 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