node.js操作数据库

1、在cmd下运行npm install mysql, 会把Node.js需要的mysql模块安装到当前位置的node_modules目录中。所以最好要把cmd的目录先定位写代码的文件夹下。

2、编写index_mysql.js代码:

var http = require('http');  
 
http.createServer(function(request, response){  
    response.writeHead(200,{'Content-Type':'text/plain'});  
    readMysql(response);
    
}).listen(8124);  
 
console.log('Server is running');  


function readMysql(response){
var mysql = require('mysql');  
 
var TEST_DATABASE = 'nodejs_mysql';  
var TEST_TABLE = 'z_t_user';  
 
//创建连接   
var client = mysql.createConnection({  
  host:'localhost',   
  port:'5522',
  user: 'root',  
  password: '123456',  
});  
 
//创建数据库   
client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {  
  if (err && err.number != mysql.ERROR_DB_CREATE_EXISTS) {  
    throw err;  
  }  
});  
 
//不指定回调函数,如果出错,则体现为客户端错误   
client.query('USE '+TEST_DATABASE);  
 
//创建表格,插入数据   
client.query(  
  'CREATE TABLE '+TEST_TABLE+  
  '(id INT(11) AUTO_INCREMENT, '+  
  'name VARCHAR(255), '+  
  'PRIMARY KEY (id))'  
);  
 
client.query(  
  'INSERT INTO '+TEST_TABLE+' '+  
  'SET name = ?',  
  ['nodejs1']  
);  
 
var query = client.query(  
  'INSERT INTO '+TEST_TABLE+' '+  
  'SET name = ?',  
  ['nodejs2']  
);  
 
//查询,并设置回调函数   
client.query(  
  'SELECT * FROM '+TEST_TABLE,  
  function selectCb(err, results, fields) {  
    if (err) {  
      throw err;  
    }  
 
    console.log(results);  
    console.log(fields);
    var firstresult = results[0];
    response.write("the database data1 is " + firstresult["name"] + "\n");
    var secondresult = results[1];
    response.write("the database data2 is " + secondresult["name"] + "\n");
    response.end('Hello Wangle, you are right, the world is right.\n');  
//    response.write(fields);
    client.end();  
  }  
);  

}

3、启动node创建的HTTP服务器(node index_mysql.js), 在浏览器中输入“http://localhost:8124/”,就可以在界面上看到数据库中存储的数据了。

注:我们来看看nodejs和数据库的交互效果,异步的IO模型一般都是在并发操作数据库读写的时候才能体现出优势来,所以如何能做到数据库操作非阻塞才是最重要的。我们现有的后台php,perl等脚本语言在操作数据库上面都存在很大的性能瓶颈,无怪乎催生了这么多的nosql产品。但是它们都没有从根本上解决数据库读写的阻塞问题。

以上功能虽然很简单,我们用php,c也能很轻易实现。但是正如nodejs所宣扬的那样,它是提供非阻塞IO的数据库操作,单进程便能处理高并发的访问。
不同的操作系统平台提供的非阻塞编程的机制是不同的,而nodejs的出现很好地统一了各个平台,对于一些轻量级的业务可以考虑直接用nodejs来处理,javascript作为一个函数式语言也有很多灵活的特性(闭包,函数即变量)我们在前台已经见识过它强大的业务处理能力,那就再期待它在服务器端的表现吧。

原文地址:https://www.cnblogs.com/wangle1001986/p/3071213.html