Node.js 连接 MySQL 并进行数据库操作

来源(开源中国社区)

From: http://www.oschina.net/code/snippet_12_3820

Node.js 连接 MySQL 并进行数据库操作

红薯 发布于 2011年04月08日 8时, 19评/19131阅

Node.js是一套用来编写高性能网络服务器的JavaScript工具包

标签: MySQL Node.js 精华

代码片段(6) [全屏查看所有代码]

1. [代码]安装 node-mysql

$ npm install mysql


2. [代码]创建测试表

//数据库名 NodeSample
 
CREATE TABLE `NodeSample`.`MyTable` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `firstname` VARCHAR( 20 ) NOT NULL ,
  `lastname` VARCHAR( 20 ) NOT NULL ,
  `message` TEXT NOT NULL
) ENGINE = MYISAM ;


3. [代码]连接数据库

var sys = require('sys');
  
var Client = require('mysql').Client;
var client = new Client();
  
client.user = 'someuser';
client.password = 'password';
  
client.connect(function(error, results) {
  if(error) {
    console.log('Connection Error: ' + error.message);
    return;
  }
  console.log('Connected to MySQL');
});


4. [代码]打开数据库

ClientConnectionReady = function(client)
{
    client.query('USE NodeSample', function(error, results) {
        if(error) {
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
    });
};


5. [代码]完成数据库操作程序

var sys = require('sys');
  
var Client = require('mysql').Client;
var client = new Client();
  
client.user = 'someuser';
client.password = 'password';
  
console.log('Connecting to MySQL...');
  
client.connect(function(error, results) {
  if(error) {
    console.log('Connection Error: ' + error.message);
    return;
  }
  console.log('Connected to MySQL');
  ClientConnectionReady(client);
});
  
ClientConnectionReady = function(client)
{
    client.query('USE NodeSample', function(error, results) {
        if(error) {
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
        ClientReady(client);
    });
};
  
ClientReady = function(client)
{
  var values = ['Chad', 'Lung', 'Hello World'];
  client.query('INSERT INTO MyTable SET firstname = ?, lastname = ? , message = ?', values,
    function(error, results) {
      if(error) {
        console.log("ClientReady Error: " + error.message);
        client.end();
        return;
      }
      console.log('Inserted: ' + results.affectedRows + ' row.');
      console.log('Id inserted: ' + results.insertId);
    }
  );
  GetData(client);
}
  
GetData = function(client)
{
  client.query(
    'SELECT * FROM MyTable',
    function selectCb(error, results, fields) {
      if (error) {
          console.log('GetData Error: ' + error.message);
          client.end();
          return;
      }
      // Uncomment these if you want lots of feedback
      //console.log('Results:');
      //console.log(results);
      //console.log('Field metadata:');
      //console.log(fields);
      //console.log(sys.inspect(results));
  
      if(results.length > 0)
      {
        var firstResult = results[0];
        console.log('First Name: ' + firstResult['firstname']);
        console.log('Last Name: ' + firstResult['lastname']);
        console.log('Message: ' + firstResult['message']);
      }
  });
  
  client.end();
  console.log('Connection closed');
};


6. [图片] 程序执行结果







9楼:shenxiangfeng 发表于 2012-03-18 22:11

好像现在版本升级了,connect() is now done automatically,我的更新代码:
var sys = require('util'); 
console.log('Connecting to MySQL...'); 
var client = require('mysql').createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
console.log('Connected to MySQL automatically');

ClientConnectionReady = function(client) 
{
    console.log('ClientConnectionReady'); 
    client.query('USE NodeSample', function(error, results) { 
        if(error) { 
            console.log('ClientConnectionReady Error: ' + error.message); 
            client.end(); 
            return; 
        } 
        ClientReady(client); 
    }); 
}; 

ClientReady = function(client) 
{ 
    var values = ['Chad', 'Lung', 'Hello World']; 
    client.query('INSERT INTO MyTable SET firstname = ?, lastname = ? , message = ?', values, 
        function(error, results) { 
            if(error) { 
                console.log("ClientReady Error: " + error.message); 
                client.end(); 
                return; 
            } 
            console.log('Inserted: ' + results.affectedRows + ' row.'); 
            console.log('Id inserted: ' + results.insertId); 
        } 
    ); 
    GetData(client); 
}

GetData = function(client) 
{ 
    client.query( 
        'SELECT * FROM MyTable', 
        function selectCb(error, results, fields) { 
            if (error) { 
                console.log('GetData Error: ' + error.message); 
                client.end(); 
                return; 
           } 

           // Uncomment these if you want lots of feedback 
           console.log('Results:'); 
           console.log(results); 
           console.log('Field metadata:'); 
           console.log(fields); 
           console.log(sys.inspect(results)); 
           if(results.length > 0) 
           { 
               var firstResult = results[0]; 
               console.log('First Name: ' + firstResult['firstname']); 
               console.log('Last Name: ' + firstResult['lastname']); 
               console.log('Message: ' + firstResult['message']); 
           } 
    }); 
    client.end(); 
    console.log('Connection closed'); 
};
ClientConnectionReady(client); 

Link: http://www.asm32.net/article_details.aspx?id=6104


浏览次数 0 发布时间 2014-01-30 00:08:47 从属分类 node.js 【评论】【 】【打印】【关闭
 
| www.asm32.net | 2006版 | 资料中心 | linux | asm/asm32 | C/C++ | VC++ | java | Python | 书签 | ASP.Net书签 | 京ICP备09029108号-1