Manipulating JMeter JDBC connection fields in Java

2019-08-13 22:49发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-08-13 23:26

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

查看更多
登录 后发表回答