简体   繁体   English

如何访问AWS Lambda中的SQL数据库?

[英]How to access SQL database in AWS Lambda?

How can I establish a connection with the SQL database in Lambda function using Node.js?如何使用Node.js与Lambda function中的SQL数据库建立连接? I want to get and post data in SQL database.我想在 SQL 数据库中获取和发布数据。

Thanks谢谢

Running nodejs code in lambda is same as running same code on any other server or your local machine.在 lambda 中运行 nodejs 代码与在任何其他服务器或本地机器上运行相同的代码相同。 You get the same nodejs runtime.您将获得相同的 nodejs 运行时。 There might be limitations when it comes to lambda such as package size, but there is no difference in how the code is executed.对于 lambda,可能存在一些限制,例如包大小,但代码的执行方式没有区别。

The link below shows, how to connect to mysql from nodejs https://www.w3schools.com/nodejs/nodejs_mysql_select.asp下面的链接显示,如何从 nodejs https://www.w3schools.com/nodejs/nodejs_mysql_select.asp连接到 mysql

if you are specifically expecting mysql in lambda, this article may be a good start.如果您特别期待 lambda 中的 mysql,这篇文章可能是一个好的开始。 https://blog.risingstack.com/getting-started-with-aws-lambda-and-node-js/ 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.或者,如果您想将 mssql 与 lambda 一起使用,请查看这个 SO 问题。 AWS Lambda and SQL Server Integration AWS Lambda 和 SQL Server 集成

I'm posting a complete lambda function that works with the SQL database.我正在发布一个与 SQL 数据库一起使用的完整 lambda 函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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