I am looking for a mySQL driver for nodejs that supports stored procedures. http://nodejsdb.org/db-mysql/ that I have been using gives the error
PROCEDURE can\'t r
it works in nodejs-mysql-native
stored procedure:
DELIMITER //
CREATE PROCEDURE test1p1()
BEGIN
SELECT 1+1;
END //
DELIMITER ;
node.js script:
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!');
});
output:
{ '1+1': 2 }
OK!
Felix Geisendörfer's node-mysql supports stored procedures, but you need to end your stored procedure by SELECT
ing a success/failure flag, then query it as you would a SELECT
query. Here's how the stored procedure might look:
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 ;
Your Node code would look something like this:
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 ...
}
});
Putting multiple solutions together for completeness
Stored Procedure:
CREATE PROCEDURE GetStudent(id int)
BEGIN
SELECT * FROM student where userid = id ;
END;
Node.js and Express code:
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');
});
(Source credits: Pushker Yadav and "http://www.javascriptpoint.com/nodejs-mysql-tutorial-example/")
node-mysql driver work with stored procedure and its very simple just call your stored procedure with parameter.
CREATE PROCEDURE GetAllStudent(id int)
BEGIN
SELECT * FROM student where userid = id ;
END;
and in node just call
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();
});
this way no need to worry of sql injection.
here is good tutorial on nodejs and mysql
Although this has been answered, I'll contribute with my own version, hope it helps you and anyone else that stumbles upon this post
In your case, this is how I would, in a single file, do (the 2019 way, kinda...) what you're trying to achieve (no need for anything other then express framework and the default mysql package that mostly everyone uses)
First, install these two packages:
Second, create a stored procedure like so:
DELIMITER //
DROP PROCEDURE IF EXISTS myProcedure //
CREATE PROCEDURE myProcedure()
BEGIN
SELECT 'hello from procedure' AS message;
END //
DELIMITER ;
And finally, create a node js script, open it and write the following lines of code:
//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'));