2016-01-14 16 views
0

我有上sails.jssails.js運行多個命令查詢在MySQL

我想在sails lift運行從文件腳本中執行多個SQL查詢的問題。

我寫了一個自定義的處理內/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; 

有沒有執行這個文件的方法嗎?

回答

0

您可以分割文件中的行,並逐個運行所有查詢?

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(); 
      } 
     ); 
    }); 
}; 
+0

如果我的一個查詢是多行的,該怎麼辦? – Tomasz

+0

你可以用';'或其他分隔符來分割嗎? – elssar

+0

嘗試通過分隔符分割命令。不在這裏工作 – Tomasz