在nodejs上是否有支持存储过程的mysql驱动程序?

时间:2012-05-11 07:07:02

标签: mysql node.js stored-procedures

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

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

5 个答案:

答案 0 :(得分:11)

FelixGeisendö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 ...

    }
});

答案 1 :(得分:4)

适用于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!

答案 2 :(得分:3)

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 :(得分:1)

尽管已经回答了这个问题,但我会提供自己的版本,希望对您和其他偶然发现本文的人有帮助

在您的情况下,这就是我将在一个文件中执行(2019年的方式,有点...)您要达到的目的(除了表达框架和默认的mysql包,不需要其他任何操作)大多数人都使用的

首先,安装以下两个软件包:

第二,创建一个存储过程,如下所示:

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

最后,创建一个节点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')); 

答案 4 :(得分:0)

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

存储过程:

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/”)