使用Node做Web頁面開發,基本上是串連非關係型資料庫mongodb,而這裡我還是先嘗試串連了一下mysql資料庫,因為相對於mysql來說mongodb過於生疏,想著快速出來頁面,所以選擇相對熟悉一些的mysql。
1. 安裝mysql
下載MySQL :MySQL Downloads,並進行安裝。安裝完,會引導你對資料庫進行配置,設定root密碼以及建立普通使用者以及密碼。
2. 安裝Node-mysql
通過npm安裝mysql的軟體包,通過它方便快速調用函數串連mysql資料庫。進入專案檔夾,執行npm install mysql --save就行了。
安裝完,在專案檔夾的node_modules目錄下會產生mysql的目錄。
3. 查看readme文檔
進入mysql目錄中,查看README文檔,這步很重要,不要到處百度Google搜尋怎麼用,因為由於版本的不一樣,也許你得到的答案並不能使你成功串連資料庫。畢竟Node發展如此之快。
如果你認真讀了README文檔,接下來的步驟就不用再看了,避免由於版本不一致而誤導你。
4. 串連mysql資料庫
進入項目文檔,建立TestMysql.js樣本,編寫如下代碼:
var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db'});connection.connect();connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution);});connection.end();
串連基本參數
- host 主機名稱,localhost代表本地
- user Mysql使用者
- password 密碼
- database 串連的資料庫
client.connect()串連資料庫
client.query()執行SQL語句
client.end()關閉串連。
然後通過node TestMysql.js執行程式,確保你在執行之前已經啟動了Mysql服務。
5. 增刪改查
使用資料庫無外乎增刪改查,下面樣本可能會對你有些協助。
var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db'});connection.connect();// 增加記錄client.query('insert into test (username ,password) values ("lupeng" , "123456")');// 刪除記錄client.query('delete from test where username = "lupeng"');// 修改記錄client.query('update test set username = "pengloo53" where username = "lupeng"');// 查詢記錄client.query("select * from test" , function selectTable(err, rows, fields){ if (err){ throw err; } if (rows){ for(var i = 0 ; i < rows.length ; i++){ console.log("%d\t%s\t%s", rows[i].id,rows[i].username,rows[i].password); } }});connection.end();
到此,Mysql資料庫的初步串連就告一段落了,接下來就可以在Node項目中自行發揮了。
希望大家繼續關注。