NodeJS初探之二——与Mysql的交互

引言: 继前面的NodeJS的Hello,World!我们还可以看到其他强大之处,NodeJS现在社区的火热,以及大批工程师对它的支持之下,现在已经陆续的引出了大量的module出来了。


内容: 下面这个所演示的是NodeJS与Mysql 的交互。

这时需要为NodeJS加入Mysql 的Module了,这时前一章说到的npm(Node package manager)启到作用了。


    把Mysql Module装到NodeJS中

Js代码  收藏代码
  1. $npm install Mysql   

 

  JS脚本 mysqlTest.js

Js代码  收藏代码
  1. // mysqlTest.js  
  2. //加载mysql Module  
  3. var Client = require('mysql').Client,  
  4.     client = new Client(),  
  5.     
  6.   //要创建的数据库名  
  7.     TEST_DATABASE = 'nodejs_mysql_test',  
  8.     //要创建的表名  
  9.     TEST_TABLE = 'test';  
  10.   
  11. //用户名  
  12. client.user = 'root';  
  13. //密码  
  14. client.password = 'root';  
  15. //创建连接  
  16. client.connect();  
  17.   
  18. client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {  
  19.   if (err && err.number != Client.ERROR_DB_CREATE_EXISTS) {  
  20.     throw err;  
  21.   }  
  22. });  
  23.   
  24. // If no callback is provided, any errors will be emitted as `'error'`  
  25. // events by the client  
  26. client.query('USE '+TEST_DATABASE);  
  27. client.query(  
  28.   'CREATE TABLE '+TEST_TABLE+  
  29.   '(id INT(11) AUTO_INCREMENT, '+  
  30.   'title VARCHAR(255), '+  
  31.   'text TEXT, '+  
  32.   'created DATETIME, '+  
  33.   'PRIMARY KEY (id))'  
  34. );  
  35.   
  36. client.query(  
  37.   'INSERT INTO '+TEST_TABLE+' '+  
  38.   'SET title = ?, text = ?, created = ?',  
  39.   ['super cool''this is a nice text''2010-08-16 10:00:23']  
  40. );  
  41.   
  42. var query = client.query(  
  43.   'INSERT INTO '+TEST_TABLE+' '+  
  44.   'SET title = ?, text = ?, created = ?',  
  45.   ['another entry''because 2 entries make a better test''2010-08-16 12:42:15']  
  46. );  
  47.   
  48. client.query(  
  49.   'SELECT * FROM '+TEST_TABLE,  
  50.   function selectCb(err, results, fields) {  
  51.     if (err) {  
  52.       throw err;  
  53.     }  
  54.   
  55.     console.log(results);  
  56.     console.log(fields);  
  57.     client.end();  
  58.   }  
  59. );  

 

  执行脚本

Js代码  收藏代码
  1. root@sammor-desktop:/var/iapps/nodejs/work# node mysqlTest.js   

 

    这时,Mysql数据库结果 显示:

    


原文地址:https://www.cnblogs.com/rmbteam/p/2124884.html