首頁  >  文章  >  web前端  >  NodeJS與Mysql的互動範例程式碼_javascript技巧

NodeJS與Mysql的互動範例程式碼_javascript技巧

WBOY
WBOY原創
2016-05-16 17:25:301308瀏覽

把Mysql Module裝到NodeJS中

Js程式碼

複製程式碼


程式碼
$npm install Mysql


JS腳本mysqlTest.js
Js程式碼複製程式碼

複製程式碼



複製程式碼



複製程式碼



複製程式碼



複製程式碼



複製程式碼



複製碼🎜> 程式碼如下:


// mysqlTest.js
//載入mysql Module
var Client = require('mysql').Client,
client = new Client(client = new Client(client ),
  
  //要創建的數據庫名
TEST_DATABASE = 'nodejs_mysql_test',
//要創建的表名
TEST_TABLE = 'test';

/ /使用者名稱
client.user = 'root';
//密碼
client.password = 'root';
//建立連線
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(
'CREATE TABLE ' TEST_TABLE
'(id INT(11) AUTO_INCREMENT, '
'title VARCHAR(255), '
'text TEXT, '
' DATETIME, '
'PRIMARY KEY (id))'
);

client.query(
'INSERT INTO ' TEST_TABLE ' '
'SET title = ?, texttext = ?, 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) { NodeJS與Mysql的互動範例程式碼_javascript技巧if (err) { throw err; } console.log(results); console.log(fields); client.end (); } ); 執行腳本Js程式碼複製程式碼複製程式碼複製程式碼複製程式碼複製程式碼複製碼> 程式碼如下: root@sammor-desktop:/var/iapps/nodejs/work# node mysqlTest.js
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn