How to create a lambda function to insert some records in an Aurora Database in AWS. Here is some sample code. This will enable us to link to databases in AWS to perform some functions.
import sys import logging import rds_config import pymysql #rds settings rds_host = "auroratest.xxxx.ap-southeast-2.rds.amazonaws.com" name = rds_config.db_username password = rds_config.db_password db_name = rds_config.db_name logger = logging.getLogger() logger.setLevel(logging.INFO) try: conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5) except: logger.error("ERROR: Unexpected error: Could not connect to MySql instance.") sys.exit() logger.info("SUCCESS: Connection to RDS mysql instance succeeded") def handler(event, context): """ This function fetches content from mysql RDS instance """ item_count = 0 with conn.cursor() as cur: cur.execute("create table Employee3 ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))") cur.execute('insert into Employee3 (EmpID, Name) values(1, "Mark")') cur.execute('insert into Employee3 (EmpID, Name) values(2, "Rob")') cur.execute('insert into Employee3 (EmpID, Name) values(3, "Manoj")') conn.commit() cur.execute("select * from Employee3") for row in cur: item_count += 1 logger.info(row) #print(row) return "Added %d items from RDS MySQL table" %(item_count)
You also need to create a configuration file that contains the user name, password and database name
db_username = "user" db_password = "password" db_name = "AURORATEST"
You can execute the function like this from opening a database connection from MySQL Workbench
call mysql.lambda_async('arn:aws:lambda:ap-southeast-2:319596327168:function:MARKTEST','')