本文介绍了带有节点MySQL的无服务器框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在无服务器框架中使用mysql连接.连接应该在我的组件函数中可用,而无需每次在组件函数中创建mysql连接

How to use mysql connection with serverless framework.connection should be available in my component functions without creating mysql connection each time in component function

尝试过

var mysql  = require('mysql');

module.exports.respond = function(event, cb) {

   var pool      =    mysql.createPool({
        connectionLimit : 100,
        host     : 'hostname',
        user     : 'username',
        password : 'password',
        database : 'databasename',
        debug    :  false
    });
    var message='';
    pool.getConnection(function(err,connection){
        if(err) {
            message='Could not connect to database';
        } else {
            message="Database is connected";
        }
        var response = {
            message: message
        };
        return cb(null, response);
    });


};

但是上面的代码仅适用于当前功能,想在无服务器框架中使mysql连接变得通用,找不到关于如何在无服务器框架中使用mysql的适当文档

but above code will be only available for current function,want to make common thing for mysql connection in serverless framework,can not find proper document about how to use mysql in serverless framework

推荐答案

我正在写自己的问题的答案

I am writing answer of my own question

component/lib文件夹中制作database.js文件

database.js代码

code of database.js

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'hostname',
    user     : 'username',
    password : 'password',
    database : 'databasename'
});

connection.connect();
module.exports = connection;

component/lib/index.js文件中创建了这样的对象

created object like this in component/lib/index.js file

var connection = require("../lib/database.js");

可以使用连接变量在component/lib/index.js

module.exports.respond = function(event, cb) {

    var query="SELECT * from table_name";

    connection.query(query,function(err,rows) {

    })
};

这篇关于带有节点MySQL的无服务器框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 09:52