Node.js中调用mysql存储过程示例_node.js
1、安装node.js、mysql,此处略(自行搜索吧)…;
2、创建一个名为test的数据库,然后建一张名为user_info的表(仅供测试)…
这里假定mysql使用的用户名为root,密码为123456
相应的mysql如下:
/**
* 创建名为test的数据库
*/
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
/**
* 创建user_info表
*/
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`userId` int(10) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) DEFAULT NULL,
PRIMARY KEY (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/**
* 插入三条记录
*/
INSERT INTO user_info VALUES (NULL, '张一'), (NULL, '张二'), (NULL, '张三');
3、创建存储过程(写的很冗余,故意的… 正好学习一下语法>_
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`proc_simple`$$
CREATE PROCEDURE proc_simple(IN uid INT(10), OUT uName VARCHAR(2), OUT totalCount INT)
BEGIN
DECLARE str_name VARCHAR(20);
SET @str_name = '';
SET totalCount = 0;
SELECT COUNT(1),userName INTO totalCount,@str_name FROM user_info WHERE userId = uid;
SET uName = @str_name;
SELECT uName, totalCount;
END$$
DELIMITER ;
4、写程序进行调用(假定存为名为sql.js的文件);
/**
* Created with JetBrains WebStorm.
* User: Meteoric_cry
* Date: 12-12-28
* Time: 上午00:18
* To change this template use File | Settings | File Templates.
*/
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
port : 3306,
user : 'root',
password : '123456',
database : 'test',
charset : 'UTF8_GENERAL_CI',
debug : false
});
connection.connect();
connection.query('CALL proc_simple(1, @a, @b);', function(err, rows, fields) {
if (err) {
throw err;
}
var results = rows[0];
var row = results[0];
console.log("userName:",row.uName, " count:", row.totalCount);
});
connection.end();
5、运行示例程序;