【问题标题】:Is there a driver for mysql on nodejs that supports stored procedures?nodejs上是否有支持存储过程的mysql驱动程序?
【发布时间】:2012-05-19 18:58:03
【问题描述】:

我正在寻找支持存储过程的 nodejs 的 mySQL 驱动程序。我一直在使用的http://nodejsdb.org/db-mysql/ 给出了错误

PROCEDURE 无法返回给定上下文中的结果集

【问题讨论】:

标签: mysql node.js stored-procedures


【解决方案1】:

Felix Geisendörfer 的node-mysql 支持存储过程,但您需要通过SELECT 输入成功/失败标志来结束存储过程,然后像使用SELECT 查询一样查询它。以下是存储过程的外观:

DELIMITER //
DROP PROCEDURE IF EXISTS MyProcedure //
CREATE PROCEDURE MyProcedure(IN param1 VARCHAR/*, My, Parameters, ... */)
BEGIN

    DECLARE EXIT HANDLER FOR NOT FOUND, SQLWARNING, SQLEXCEPTION SELECT 0 AS res;
    # My Queries etc. ...

    SELECT 1 AS res;

END //
DELIMITER ;

您的节点代码如下所示:

var mysql = require('mysql');

var client = mysql.createConnection({
    host    : '127.0.0.1',
    user    : 'username',
    password: 'password'
});
client.query('USE mydatabase');

var myParams = "'param1', 'param2', ... ";
client.query("CALL MyProcedure(" + myParams + ")", function(err, results, fields) {
    if (err || results[0].res === 0) {
        throw new Error("My Error ... ");
    } else {
        // My Callback Stuff ...

    }
});

【讨论】:

  • 你必须对参数值的这个字符串连接开玩笑。你想要 SQL 注入吗?这就是我们获得 SQL 注入的方式。
  • 也许应该更新示例以显示如何正确转义,例如npmjs.com/package/mysql#escaping-query-values
  • 您可以简单地使用 + client.escape(myParams) + 进行转义
【解决方案2】:

node-mysql 驱动程序使用存储过程,它非常简单,只需使用参数调用您的存储过程。

CREATE PROCEDURE GetAllStudent(id int)
BEGIN
SELECT * FROM student where userid = id ;
END;

在节点中调用

app.get('/sp', function (req, res, next) {
    connection.connect();
    connection.query('CALL GetAllStudent(?)',[req.body.id],function (err, rows, fields) {
        if (err) {
            res.status(400).send(err);
        }
        res.status(200).send(rows);
    });

    connection.end();
});

这样就不用担心sql注入了。

here是nodejs和mysql的好教程

【讨论】:

    【解决方案3】:

    它适用于nodejs-mysql-native

    存储过程:

    DELIMITER //
    CREATE PROCEDURE test1p1()
      BEGIN
      SELECT 1+1;
      END //
    DELIMITER ;
    

    node.js 脚本:

    mysql = require('mysql-native');
    var db = mysql.createTCPClient();
        db.auth('test', 'tester', ''); // db, user, password
    
    db.query('call test.test1p1;').on('row', function(r) {
        console.log(r);
    }).on('end', function() {
        console.log('OK!');
    });
    

    输出:

    { '1+1': 2 }
    OK!
    

    【讨论】:

      【解决方案4】:

      虽然已经回答了这个问题,但我会贡献我自己的版本,希望它可以帮助你和其他任何偶然发现这篇文章的人

      在您的情况下,这就是我将如何在单个文件中执行(2019 年的方式,有点...)您想要实现的目标(除了 express 框架和默认的 mysql 包之外,不需要任何其他东西大多数人都使用)

      首先,安装这两个包:

      其次,像这样创建一个存储过程:

      DELIMITER //
      DROP PROCEDURE IF EXISTS myProcedure //
      CREATE PROCEDURE myProcedure()
        BEGIN
          SELECT 'hello from procedure' AS message;
        END //
      DELIMITER ;
      

      最后,创建一个 node js 脚本,打开它并编写以下代码行:

      //handles the requests/responses in your API
      const express = require('express');
      
      //handles the mysql stuff 
      const mysql = require('mysql');
      
      
      const app = express(); //create your express based app
      
      //database access config
      const config = {
        host: '127.0.0.1',
        user: 'username',
        password: 'password'
        database: 'test-db'
      }
      
      //Example route(you can add more of these for POST, PATCH and so on)
      //If you need other methods just change the 'app.get' to 'app.<method here>'.
      app.get('/test-route', (req, res) => { 
        try
        {
          const dbConn = mysql.createConnection(config); //creates a connection with the config above
          dbConn.connect((err) => { //connect to the db
            if(err)//if the connection fails log and send a error response
            {
              console.log(`Error: ${err.stack}`);
              res.status(500).send({error: "Something went wrong."});
            }
            else
            {
              let stmt = `CALL myProcedure();`; //sql query for running the example procedure 
      
              //You don't need to wrap anything in a try catch block if you don't mind 
              //your app crashing if any mysql related errors occur.
              //Console.log isn't required either. 
              //Use these above only if you need.
              try 
              {
                dbConn.query(stmt, (err, rows) => {
                  if(err)//if the query fails log and send a error response
                  {
                    console.log(`Error: ${err.stack}`);
                    res.status(500).send({error: "Something went wrong."});
                  }
                  else
                  {
                    try
                    {
                      //closes the connection and sends the result of executing the procedure
                      dbConn.end();
                      res.send({message: rows[0][0].message});
                    }
                    catch(err)
                    {
                      console.log(`Error: ${err.stack}`);
                      res.status(500).send({error: "Something went wrong."});
                    }
                  }
                });
              }
              catch(err) 
              {
                console.log(`Error: ${err.stack}`);
                res.status(500).send({error: "Something went wrong."});
              }
            }
          });
        }
        catch(err)
        {
          console.log(`Error: ${err.stack}`);
          res.status(500).send({error: "Something went wrong."});
        }
      }
      
      //this must always be your last line of code in order
      //for you to be able to run your express app
      app.listen(5555, () => console.log('Server running...\nListening on port: 5555')); 
      

      【讨论】:

        【解决方案5】:

        将多个解决方案放在一起以确保完整性

        存储过程:

        CREATE PROCEDURE GetStudent(id int)
        BEGIN
        SELECT * FROM student where userid = id ;
        END;
        

        Node.js 和 Express 代码:

        var express = require('express');
        var mysql = require("mysql");
        var
        
        app = express();
        
        var pool = mysql.createPool({
            connectionLimit: 100,
            host: 'localhost',
            user: 'root',
            password: '',
            database: 'demo'
        });
        
        app.get('/pool', function (req, res) {
        
            var studentId = req.body.id;
        
            pool.getConnection(function (err, connection) {
                // connected! (unless `err` is set)
                if (err) {
                    res.status(400).send(err);
                }
                connection.query('CALL GetStudent(?)',[studentId], function (err, rows, fields) {
                     connection.release();
                     if (err) {
                        res.status(400).send(err);
                    }
                    res.status(200).send(rows);
                });     
            });
        });
        
        app.listen(4000, function () {
            console.log('Server is running.. on Port 4000');
        });
        

        (来源:Pushker Yadav 和“http://www.javascriptpoint.com/nodejs-mysql-tutorial-example/”)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-27
          • 1970-01-01
          • 2017-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-18
          • 1970-01-01
          相关资源
          最近更新 更多