Create BeanShell Script to Make Database call

BeanShell Script

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.


Following script make database connection and every iteration it takes 50 records from database and populate them in hashmap. This has been created to use with jmeter using beanshell sampler.

 import com.postgresql.jdbc.Driver;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.Statement;  
 import java.util.HashMap;  
 import java.util.Map;  
   System.out.println("Postgres Connect Example.");  
   Connection conn = null;  
   Statement stmt = null;  
   ResultSet rs = null;  
   String url = "jdbc:postgresql://192.168.3.99:5432/";  
   String dbName = "DB";  
   String driver = "org.postgresql.Driver";  
   String userName = "username";  
   String password = "pwd";  
   Map recordMap = new HashMap();  
   try {  
     Class.forName(driver);  
     System.out.println("Connecting to a selected database...");  
     conn = DriverManager.getConnection(url + dbName, userName, password);  
     System.out.println("Connected database successfully...");  
     System.out.println("Creating statement...");  
     stmt = conn.createStatement();  
     for (int count = 0; count < 50; count++) {  
       String sql = "select b.id, tf.rec_locator, pax.first_name, pax.last_name, bc.email1, bc.home_phone "  
             + "from booking b inner join tripinfo tf on b.id = tf.booking_id inner join paxdetails pax on pax.booking_id = b.id "  
             + " inner join booking_contact bc on bc.booking_id = b.id order by 1 desc limit 50 offset " + count * 50;          
     System.out.println("SQL IS : " + sql);  
     rs = stmt.executeQuery(sql);  
     while (rs.next()) {  
       String detail = "Records : " + rs.getInt(1) + "-" + rs.getString(2) + ":" + rs.getString(3) + " " + rs.getString(4)  
         + "::" + rs.getString(5) + "-" + rs.getString(6);  
       recordMap.put(String.valueOf(rs.getInt(1)), detail);  
       System.out.println(detail);  
     }  
    }  
   rs.close();  
   } catch (Exception e) {  
     System.out.println("Something wron went");  
     e.printStackTrace();  
   }  
 System.out.println(recordMap);  
 return "Execution Complete"  

Happy Reading...!!!

Comments

  1. This comment has been removed by the author.

    ReplyDelete
  2. I am having an issue with running this script in a jmeter script, do you have the full jmeter script?

    ReplyDelete

Post a Comment

Popular posts from this blog

JAX-WS - SOAP Handlers

Connection Pooling