Manipulating JMeter JDBC connection fields in Java/beanshell code

橙三吉。 提交于 2019-12-13 02:34:22

问题


This is a followup to Using a JMeter JDBC connection in Java code. How do I use the methods such as getPassword() or getUsername in the DataSourceElement class? I want to get and then modify the username and password (among other things) from the JDBC Connection Configuration config.

I'm using the same code in that post, but in a beanshell sampler (which will ultimately be used in a preprocessor element). I think the problem is that I need a DataSourceElement object and have only defined a Connection object. That is where I am stuck.

My code:

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 returns this:

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'

And the console output returns the connection object and then stops at the error:

beanshell script beginning
org.postgresql.jdbc4.Jdbc4Connection@7849e2a7

回答1:


It is possible to get some connection information using DatabaseMetaData class like:

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);

But I don't think you will be able to get the password this way as the ability would cause immense security risks.

By the way, you can get more friendly exception message in jmeter.log file by surrounding your Beanshell code into try/catch block like:

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

See How to Use BeanShell: JMeter's Favorite Built-in Component for more information on using JMeter and Java APIs from Beanshell test elements



来源:https://stackoverflow.com/questions/36779835/manipulating-jmeter-jdbc-connection-fields-in-java-beanshell-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!