hello and welcome to red stapler in this video I'm going to show you how to
connect to RDS MySQL database from AWS lambda first you need to have database
instance running on RDS here's the database I have just only one employee
table with couple rows so I'm going to make a lambda function connect to new
database and select the first employee no need to use nodejs MySQL module for
this job which is not natively available on lambda so we need to code and test
locally and then create a deployment package and upload it back to lambda so
let's begin with initializing the project with NPM init
and then install mysql module with npm install. Create a new file for
local run so let's name it local.js
now rather than creating and managing the database connection one by one when
working with lamda we should utilize the connection pool instead so when your
function was invoked many times in a short period the connection can be
reused without opening and closing many times let's use the example code on
MySQL github to create a connection pool
you can get the host URL from your RDS console and database instance
now it's not a very good practice to hard-coding these values in a source
code so I'm going to create a config JSON file to hold these values
and then lock the config file from the js using require
next we use get connection method to get the connection from the pool and then
use query method to execute the SQL
and in a call back we will release the connection back to the pool for use and
then throw the errors if any are surely selected result to the console and
finally terminate the node process now let's test our code
okay that works fine so the next step is to make change to our code a little bit
so it can work with lambda let's create a copy of this code and name it main.js
we need to move get connection method inside exports.handler and then
replace the throw back and console.log with lambda callback function
we need to remove processes.exit and replace it with
context.callbackwaitforemptyeventloop equal to false we need to do this because the
connection will remain active for the connection to be reused and so if you do
not disable this flag the lambda call back we wait forever for the pool to
shut down and resulted in a timeout now we are ready let's create a deployment
package by sipping everything you need except a local address and then upload
it from the console
all right that's it hope this health getting start with lambda MySQL
connection if you liked this video please give a thumbs up and subscribe
thanks for watching and bye