分享

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

 昵称597197 2012-06-25

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


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

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


    把Mysql Module装到NodeJS中

Js代码  
 $npm install Mysql   

 

  JS脚本 mysqlTest.js

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

  59.   执行脚本
Js代码 复制代码 收藏代码
  1. root@sammor-desktop:/var/iapps/nodejs/work# node mysqlTest.js   

  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约