新聞中心
這里有您想知道的互聯網營銷解決方案
Node.js初探之與Mysql的交互
繼前面的NodeJS的Hello,World!我們還可以看到其他強大之處,NodeJS現在社區(qū)的火熱,以及大批工程師對它的支持之下,現在已經陸續(xù)的引出了大量的module出來了。

創(chuàng)新互聯建站主要從事做網站、成都做網站、網頁設計、企業(yè)做網站、公司建網站等業(yè)務。立足成都服務美蘭,十多年網站建設經驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:13518219792
內容: 下面這個所演示的是NodeJS與Mysql 的交互。
這時需要為NodeJS加入Mysql 的Module了,這時前一章說到的npm(Node package manager)啟到作用了。
把Mysql Module裝到NodeJS中
Js代碼
- $npm install Mysql
JS腳本 mysqlTest.js
Js代碼
- // mysqlTest.js
- //加載mysql Module
- var Client = require('mysql').Client,
- client = new Client(),
- //要創(chuàng)建的數據庫名
- TEST_DATABASE = 'nodejs_mysql_test',
- //要創(chuàng)建的表名
- TEST_TABLE = 'test';
- //用戶名
- client.user = 'root';
- //密碼
- client.password = 'root';
- //創(chuàng)建連接
- client.connect();
- client.query('CREATE DATABASE '+TEST_DATABASE, function(err) {
- if (err && err.number != Client.ERROR_DB_CREATE_EXISTS) {
- throw err;
- }
- });
- // If no callback is provided, any errors will be emitted as `'error'`
- // events by the client
- client.query('USE '+TEST_DATABASE);
- client.query(
- 'CREATE TABLE '+TEST_TABLE+
- '(id INT(11) AUTO_INCREMENT, '+
- 'title VARCHAR(255), '+
- 'text TEXT, '+
- 'created DATETIME, '+
- 'PRIMARY KEY (id))'
- );
- client.query(
- 'INSERT INTO '+TEST_TABLE+' '+
- 'SET title = ?, text = ?, created = ?',
- ['super cool', 'this is a nice text', '2010-08-16 10:00:23']
- );
- var query = client.query(
- 'INSERT INTO '+TEST_TABLE+' '+
- 'SET title = ?, text = ?, created = ?',
- ['another entry', 'because 2 entries make a better test', '2010-08-16 12:42:15']
- );
- client.query(
- 'SELECT * FROM '+TEST_TABLE,
- function selectCb(err, results, fields) {
- if (err) {
- throw err;
- }
- console.log(results);
- console.log(fields);
- client.end();
- }
- );
執(zhí)行腳本
Js代碼
- root@sammor-desktop:/var/iapps/nodejs/work# node mysqlTest.js
這時,Mysql數據庫結果 顯示:
原文:http://www.iteye.com/topic/968847
【編輯推薦】
- Node.js入門之神秘的服務器端JavaScript
- 什么是Node.js?
- 親愛的PHP我要離開你 因為我對NodeJs更有感
- 使用node.js進行服務器端JavaScript編程
- 淺析Node.js:一個“編碼就緒”服務器
新聞名稱:Node.js初探之與Mysql的交互
網站路徑:http://www.5511xx.com/article/dhdsjhg.html


咨詢
建站咨詢
