2017-08-25 15 views
2

NodeJSを使用してSQL Serverに接続しています。私の最初のコードは:NodeJSとSQL Serverの接続エラー

const poolA = new sql.ConnectionPool(config, err => { 
     poolA.request() 
      .query("select * from AnyTable", function(err, result) { 
       if (err) 
        message = "Error!"; 
       else {       
        //Do something else 
        message = "Done!"; 
       } 
      }) 
    }); 

「接続がクローズエラーです」というメッセージが表示されました。私は含まれています

poolA.close() 

それも問題を解決しませんでした。

私はこれを変更:

new sql.ConnectionPool(config).then(pool => { 
     pool.request() 
      .query("select * from AnyTable") 
    }).then(result => { 
     //Do something else 
     message = "Done!"; 
     sql.close(); 
    }).catch(err => { 
     message = "Error!"; 
     sql.close(); 
    }); 

、今私は、エラー ".thenは関数ではありません" を取得。

正しい方法を教えて:接続がすでに存在する場合、それは

  • 存在しない場合

    1. は、接続を作成しますが、私はエラーのすべての種類を取得しています、それ

    を使用しています。誰かがこの問題を解決する手助けをすることができますか?

  • 答えて

    1

    あなたがあなたの目のオプションで行ったように、あなたは、約束を使用する必要があるノードを使用している場合。だから、次のようにこれがあるべき正しい方法 -

    sql.close() 
        sql.connect(sqlConfig).then(pool => { 
        pool.request() 
        .input('param1', sql.Int, valueParam1) 
        .input('param2', sql.Int, valueParam2) 
        .execute(procedureToExecute).then(result => { 
         // Do whatever you want with the result. 
    }) 
    

    はそのチェーンを覚えていますかあなたが約束から任意のものを返す場合にのみ可能です。あなたのケースでは、接続プールや約束どおりのものを返していないので、".then is not a function" error.プールを再度使用したい場合や、結果を返す場合は結果を返す必要があります。

    第2の方法として、接続を一度作成してからどこでも使用できます。コンセプトは、MongoDB ConnectionPoolingのものと非常に似ていますので、詳細を確認してください。

    'use strict' 
    
    const config = require(__dirname + '/index.js') 
    , mssql = require('mssql') 
    , sqlConfig = { 
    , user: config.databaseUsername 
    , password: config.databasePassword 
    , server: config.databaseHost 
    , database: config.database.database 
    pool: { 
        max: 10, 
        min: 0, 
        idleTimeoutMillis: 30000 
        } 
    } 
    
    let connection = mssql.connect(sqlConfig,err => { 
        if (err) 
        {throw err} 
    }) 
    
    module.exports = connection 
    

    を次にワイヤー(必要)サーバーのファイルまたはあなたが以下のように接続を使用したい任意のモジュールで上記 - - この以下のようにdb.jsファイルを作成するために

    db = require(process.cwd() + '/config/db.js') 
    

    あなたは含めることができますこれは以下のようなリクエストオプションがあります -

    let options = {db:db} 
    request.options = options 
    

    これが役に立ったら、もう助けが必要な場合にお知らせください。

    0

    私はそれをテストしていないが、あなたのコードを見て、あなたは)(2番目のにどんな約束を返していないので、あなたは.thenが機能ではありません。このエラーに遭遇します。その後、最初のリターンを追加

    てみてください()

    new sql 
        .ConnectionPool(config) 
        .then(pool => { 
         return pool 
         .request() 
         .query("select * from AnyTable") 
        }) 
        .then(result => { 
         //Do something else 
         message = "Done!"; 
         sql.close(); 
        }) 
        .catch(err => { 
         message = "Error!"; 
         sql.close(); 
        });