Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions,
see Getting Started with Amazon Web Services in China
(PDF).
Connecting to an Amazon RDS database in a Lambda function
The following code example shows how to implement a Lambda function that connects to an RDS database. The function makes a simple database request and returns the result.
- JavaScript
-
- SDK for JavaScript (v2)
-
There's more on GitHub. Find the complete example and learn how to set up and run in the
Serverless examples
repository.
Reporting Kinesis batch item failures with Lambda using Javascript.
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/*
Node.js code here.
*/
// ES6+ example
import { Signer } from "@aws-sdk/rds-signer";
import mysql from 'mysql2/promise';
async function createAuthToken() {
// Define connection authentication parameters
const dbinfo = {
hostname: process.env.ProxyHostName,
port: process.env.Port,
username: process.env.DBUserName,
region: process.env.AWS_REGION,
}
// Create RDS Signer object
const signer = new Signer(dbinfo);
// Request authorization token from RDS, specifying the username
const token = await signer.getAuthToken();
return token;
}
async function dbOps() {
// Obtain auth token
const token = await createAuthToken();
// Define connection configuration
let connectionConfig = {
host: process.env.ProxyHostName,
user: process.env.DBUserName,
password: token,
database: process.env.DBName,
ssl: 'Amazon RDS'
}
// Create the connection to the DB
const conn = await mysql.createConnection(connectionConfig);
// Obtain the result of the query
const [res,] = await conn.execute('select ?+? as sum', [3, 2]);
return res;
}
export const handler = async (event) => {
// Execute database flow
const result = await dbOps();
// Return result
return {
statusCode: 200,
body: JSON.stringify("The selected sum is: " + result[0].sum)
}
};
For a complete list of Amazon SDK developer guides and code examples, see
Using this service with an Amazon SDK.
This topic also includes information about getting started and details about previous SDK versions.