How to call a MySQL stored procedure
Sometimes you might need to connect to a MySQL database and call a stored procedure. There are many ways to accomplish this task and I would like to discuss one of the ways we are using here at Walden Systems, because we believe this is the most straightforward method to connect to a MySQL database and call a stored procedure.
Strategy to connecting to a MySQL database and calling a stored procedure is straight forward and involves four steps: First, we need to include the mysql module. Second, we need to create a connection using the built in mysql method, createConnection( ). Third, we need to connect to the MySQL database using the built in mysql method, connect( ). Finally, once the MySQL connection is made, we need to call the stored procedure using the built in mysql method query ( ).
First, we need to include the mysql module and include it. If you don't have the mysql module installed, run the following command to install it using npm:
npm install mysql
Once the mysql module is installed, include it using the following line:
var mysql = require( 'msql' ) ;
Next, we will create the connection using the following code:
var con = mysql.createConnection ( { host: "HOSTNAME", user: "USERNAME", password: "PASSWORD" } ) ;
Third, we will connect to the MySQL database with the following code:
con.connect ( function ( error ) { if ( error ) { throw error ; } console.log( "Connected!" ) ; } ) ;
Finally, we will call the stored procedure with the following code:
con.query ( SOME_STORED_PROC_NAME, ( error, rows ) => { if ( error ) { throw error ; } console.log( 'Data received from Db: ' ) ; console.log( rows ) ; } ) ;
When we put the code together, we can connect to the MySQL database and get the results from the stored procedure :
var mysql = require( 'msql' ) ; var con = mysql.createConnection ( { host: "HOSTNAME", user: "USERNAME", password: "PASSWORD" } ) ; con.connect ( function ( error ) { if ( error ) { throw error ; } console.log( "Connected!" ) ; } ) ; con.query ( SOME_STORED_PROC_NAME, ( error, rows ) => { if ( error ) { throw error ; } console.log( 'Data received from Db: ' ) ; console.log( rows ) ; } ) ;