11

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

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

4

5 回答 5

13

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

    }
});
于 2012-05-21T14:29:05.773 回答
6

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注入了。

是关于nodejs和mysql的好教程

于 2016-11-21T03:54:42.973 回答
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!
于 2012-05-11T11:08:42.830 回答
1

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

就您而言,这就是我将如何在单个文件中执行(2019 年的方式,有点...)您想要实现的目标(除了表达框架和大多数人的默认 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')); 
于 2019-06-06T16:17:56.377 回答
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/ ”)

于 2017-11-24T16:48:36.753 回答