Saturday, January 21, 2017

AWS Lambda RDS connection Using Java

Java Program For Connecting to AWS RDS Database and deploying into Lambda Function.

Steps:
1. Create Simple java Project using Eclipse.

2. Create class implementing the Handler as shown in code.


package com.bridgelabz.RDSConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class RDSConnection implements RequestHandler<String, String> {
Statement statement;
ResultSet resultSet;

@Override
public String handleRequest(String input, Context context) {

// String abc=database.database(input);
try {
Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection(
"jdbc:mysql://Endpoint/DB_Name", "User_Name", "password");

context.getLogger().log("Test Started");
String query = "select * from Table_Name where id=" + input;
Statement statement = con.createStatement();
resultSet = statement.executeQuery(query);

if (resultSet.next()) {
String output = "Hello, " + resultSet.getString("name") + "!";

context.getLogger()
.log(resultSet.getString("id") + "Console: Hello " + resultSet.getString("name") + " !");
return output;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

return null;
}

}

3. Add Endpoint,DB Name,User_Name from RDS Database instance.

4. Create table inside RDS database and adding data (using Mysql Workbench to make Local Connection with RDS Database of AWS Services. RDS to Mysql Connection)

5. Export the java project into .zip/.jar file for uploading on Lambda Function.

6. Adding classpath inside the MANIFEST.MF file.

         Class-Path: path of External jars.
       Eg: Class-Path: lib/mysql-connector-java-5.0.8.jar.

7. Creating Lambda Function inside AWS.

8. Uploading Created Jar  and Giving handler for the function.

      Here Handler is packageName.ClassName
      for our program Handler Will be "com.bridgelabz.RDSConnection.RDSConnection"

9. Select vpc, subnets and Security Group which was used while making the RDS connection.

for video tutorial visit here.