- npm 的 SQLite3 網址: https://npmjs.org/package/sqlite3
- SQLite 的官網:http://www.sqlite.org/index.html
SQLite 算是比較輕便型的資料儲存方式,適合開發時的時候使用,但如果是真的 Production 的環境就沒這麼適合。其實我以前沒想過 SQLite 這麼方便,大學還在學 PHP 時看到 SQLite 的章節是直接跳過的,因為當時的公司也沒使用 SQLite :P
SQLite 有以下幾點的特質:
- 輕薄短小,使用簡單
- 沒有資料庫的伺服器,它是用檔案或是 memory 的方式儲存
- 適合開發階段使用,儲存少量資料
- 帶資料存在硬碟,存取速度稍慢
- 沒有 user 權限設定的功能,較不適合儲存個人或私密資料
使用 Node.js + SQLite3
1) 初始化專案
npm init
使用 npm init 會開始問你一些問題,通常我都直接按 Enter 讓他用預設的設定,最後產出 package.json 檔案,如果現有的專案已有 package.json,就不需要做初始化的動作。
2) 安裝 SQlite
npm install sqlite3 --save
或是npm install sqlite3
* 要先安裝 npm , 否則無法下載。
使用 npm install sqlite3 --save 安裝的話會自動幫你在 package.json 的 dependencies 的項目加上 sqlite3 , 通常我都是用這個比較方便。
3) 新增一個 test.db 檔案
用來寫入資料用的 database 檔案。
4) 新增 testdb.js 檔案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs"); | |
var file = "./test.db"; | |
//載入 sqlite3 | |
var sqlite3 = require("sqlite3").verbose(); | |
//new 一個 sqlite 的 database,檔案是 test.db | |
var db = new sqlite3.Database(file); | |
db.serialize(function() { | |
//db.run 如果 Staff 資料表不存在,那就建立 Staff 資料表 | |
db.run("CREATE TABLE IF NOT EXISTS Stuff (thing TEXT)"); | |
var stmt = db.prepare("INSERT INTO Stuff VALUES (?)"); | |
//寫進10筆資料 | |
for (var i = 0; i<10; i++) { | |
stmt.run("staff_number" + i); | |
} | |
stmt.finalize(); | |
db.each("SELECT rowid AS id, thing FROM Stuff", function(err, row) { | |
//log 出所有的資料 | |
console.log(row.id + ": " + row.thing); | |
}); | |
}); | |
db.close(); | |
5) 跑 testdb.js 這隻檔案
node testdb.js
接著就會看到 log 出來的結果。
需要小心的部分
我剛開始試的時候,一直遇到這個 Error :
Error: SQLITE_ERROR: near "Check": syntax error
後來發現是因為 create table 時出了問題,不曉得是因為我已經建立過才出錯,還是因為根本 table 不存在而出錯,後來加上 IF NOT EXISTS 做為 create table 的判斷就正常了。
參考網址:
- NODE.JS AND SQLITE http://blog.modulus.io/nodejs-and-sqlite
- node-sqlite3 的 API 文件:https://github.com/mapbox/node-sqlite3/wiki/API
沒有留言:
張貼留言
若你看的文章,時間太久遠的問題就別問了,因為我應該也忘了... XD