sails.js在mysql中运行多个命令查询

问题描述 投票:0回答:2

我在sails.js上执行多个sql查询时遇到问题

我想从sails lift上的文件运行脚本。

我在/config/bootstrap.js内写了一个自定义处理方法>

module.exports.bootstrap = function(cb) {

  fs.readFile('SQL\\StoredProcedures\\MyProcedure.sql', 'utf8', function (err,data) {
    if (err) {

      console.log(err);
    }
    console.log(data);
    MyModel.query(data, function(err, records){
        if(err){
          console.log(err);
        }
    });
  });
  // It's very important to trigger this callback method when you are finished
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
  cb();
};

问题是.query()函数在内部不接受多个查询。我的意思是,当我拥有文件时,它确实接受:

DROP PROCEDURE IF EXISTS `MyProcedure`;

但是当我拥有文件时,它将不接受:

DROP PROCEDURE IF EXISTS `MyProcedure`;
SELECT * FROM something;

是否有执行此文件的方法?

我在sails.js上执行多个sql查询时遇到问题,我想从sails lift上的文件中运行脚本。我在/config/bootstrap.js module.exports.bootstrap = ...]内部编写了一个自定义处理

您可以分割文件中的行,并一一运行所有查询?
var fs = require('fs'); module.exports = function (cb) { fs.readFile('SQL\\StoredProcedures\\MyProcedure.sql', 'utf8', function (err,data) { if (err) { sails.log.error(err); return cb(); // you have no queries to run } sails.log.info(data); var queries = data.split('\n'); // async is injected into the global scope by sails, so no need to require it // if you don't need your queries to run in order, then you can use async.each // instead of async.eachSeries // https://github.com/caolan/async#each async.eachSeries( queries, function (query, cb) { MyModel.query(query, function (err, records) { if (err) { sails.log.error(err); return cb(); // If you don't want other queries to execute in case of an error, then // return cb(err); } }); }, function (err) { if (err) { sails.log.error(err); } return cb(); } ); }); };

这可以通过如下设置config/datastores.js来完成:
module.exports = { default: { multipleStatements: true } }
通过将其添加到配置中,您可以让Sails处理查询的解析和执行。

问题是,默认情况下,Node MySQL驱动程序不允许一次运行多个查询。这是为了防止SQL注入。

有关更完整的解释,请参见此处@ sgress454的注释:https://github.com/balderdashy/sails/issues/4192
mysql sails.js waterline
2个回答
0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.