How to access SQL database in AWS Lamda?

流过昼夜 提交于 2019-12-25 01:47:41

问题


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

Thanks


回答1:


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




回答2:


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);
   }
}


来源:https://stackoverflow.com/questions/59230916/how-to-access-sql-database-in-aws-lamda

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!