简体   繁体   中英

How to access SQL database in AWS Lambda?

How can I establish a connection with the SQL database in Lambda function using Node.js? I want to get and post data in SQL database.

Thanks

Running nodejs code in lambda is same as running same code on any other server or your local machine. You get the same nodejs runtime. There might be limitations when it comes to lambda such as package size, but there is no difference in how the code is executed.

The link below shows, how to connect to mysql from nodejs https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

if you are specifically expecting mysql in lambda, this article may be a good start. https://blog.risingstack.com/getting-started-with-aws-lambda-and-node-js/

or else if you want to use mssql with lambda, look at this SO question. AWS Lambda and SQL Server Integration

I'm posting a complete lambda function that works with the SQL database.

const sql = require('mssql');

    const config = {
                     user: "username",
                     password: "password",
                     server: "server",
                     database: "database name",
                     options: {
                                   //In case of azure database
                                    encrypt: true
                               }
                   }

exports.handler = async event => 
{
  if(event.httpMethod ==='GET')
  {
    return await getRecord(event);  
  }
};

const getRecord = async event => 
{
   try 
   {
     // Open DB Connection
     let pool = await sql.connect(config)

     // Query Database
     let result = await pool.request().query('select * from tablename')

     // Close DB Connection
     pool.close();

     // The results of our query
     console.log("Results:", result);

     return 
     {
        statusCode:200,
        body:result
     }

   } 
   catch (err) 
   {
    // Error running our SQL Query
    console.error("ERROR: Exception thrown running SQL", err);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM