Skip to content

Using Mysql

Alexander edited this page Aug 4, 2019 · 2 revisions
//  ## JDBC Based JavaScript  ##
 
// Declaring the getConnection function
var getConnection = function() {
    var Properties = Java.type("java.util.Properties");
    var Driver = Java.type("com.mysql.jdbc.Driver");
    var driver = new Driver();
    var properties = new Properties();
    var conn = null;
    try {
        properties.setProperty("user", "username");
        properties.setProperty("password", "password");
        conn = driver.connect("jdbc:mysql://ip:port/db name here", properties);
        return conn;
    } finally {
    }
}
print("Connection: " + getConnection());

// Declaring the runQuery function
function runQuery(conA, query) {
    try {
        var stmt = conA.prepareStatement(query);
        var resultSet = stmt.executeQuery();
        print("      --------------------------- ");
        while (resultSet.next()) {
           print("\t" + resultSet.getInt("id") + " - "+ resultSet.getString("name"))
        }
        print("      --------------------------- ");
         
     } finally {
       if (resultSet)
          try {
             resultSet.close();
             print("\nResultSet Closed.");
          }
          catch(e) {}
       if (stmt)
          try {
             stmt.close();
             print("Statement Closed.");            
          } catch (e) { print( e );  }
       if (conA)        
          try { 
             conA.close();
             print( "Connection Closed." );
          } catch (e) { print( e );  }          
       }  
}
var con1 = getConnection();
runQuery(con1, "select * from test");