Node.js中調用mysql預存程序樣本,node.jsmysql

來源:互聯網
上載者:User

Node.js中調用mysql預存程序樣本,node.jsmysql

例子僅在windows下測試通過,沒有放在linux下測試。如有問題,可以電郵給我~

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、運行樣本程式;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.