SQLite 是一個單文件的離線關系型 SQL 數據庫,它的文件都存儲在一個 DB 數據文件中,相比 MySQL 這種數據庫服務器來說,SQLite 更方便遷移,對于內存小的服務器來說,使用 SQLite 也是一個不錯的選擇。SQLite 也可以集成到桌面應用程序中,作為本地數據庫使用。

很多編程語言都能操作 SQLite 數據庫,Node.js 也不例外。最近在寫一個 Electron 的桌面程序,需要用到 SQLite 作為本地數據庫,這里就簡單寫一下 Node.js 操作 SQLite。

安裝 sqlite3 模塊

在操作 SQLite 之前還需要先安裝 sqlite3 模塊,用 npm 安裝:

npm install sqlite3 --save-dev

如果在安裝的時候出現如下的錯誤:

gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error

SQLite 模塊的編譯需要用到 Python,可以下載 Python 安裝。

如果安裝了最新版的 Python 還是出錯的話,可以通過 npm 安裝 Python 2,如果用的是 Windows 的話可以通過管理員權限運行 Powershell ,輸入:

npm install --global windows-build-tools

安裝完 Python 后應該就可以安裝 sqlite3 模塊了。

打開數據庫

下面打開一個 data.db 的數據庫:

const sqlite3 = require('sqlite3');  // 引入 sqlite3 模塊
const path = require('path');  // 引入路徑處理模塊

const dbName = path.join(__dirname, 'data.db');  // 獲取當前運行目錄下的 data.db 文件
// 打開數據庫
const db = new sqlite3.Database(dbName, err => {
  if (err !== null) console.log(err);  // 輸出錯誤信息
});

sqlite3.Database 方法可以打開一個數據庫,如果傳入的 DB 數據庫文件不存在就會創建一個,返回一個數據庫對象。

如果要關閉打開的數據庫可以使用 close 方法,如下:

db.close(err => {
  if (err) console.log(err);
});

回調函數可以接收一個 err 也就是錯誤信息。

創建數據表

下面創建一張 user 數據表:

// SQL 語句
const sql = `
CREATE TABLE user (
  id INTEGER PRIMARY KEY,
  user_name VARCHAR (30) NOT NULL,
  age TINYINT (3) NOT NULL DEFAULT 0
)
`;
// 創建表格
db.run(sql, function(err) {
  if (err) console.log(err);  // 如果出現錯誤就輸出錯誤信息

});

這里創建表使用的是 run 方法,run 方法可以執行 SQL 語句,通過回調函數可以獲取受影響的行數。不過創建表格是無法獲取影響的行數的,只有在 增、刪、改 的時候才能獲取影響的行數。

添加數據

下面給 user 表添加一條數據:

db.run('INSERT INTO user (user_name, age) VALUES (?, ?)', ['Mark', 28], function(err) {
  if (err) console.log(err);  // 如果有錯誤就輸出錯誤信息
  console.log(this.changes);  // 輸出受影響的行數
  console.log(this.lastID);  // 輸出 lastID
});

run 方法可以用于插入、更新、刪除 數據,第一個參數的 SQL 語句中包含一些 ?,這個 ? 就是占位符,第二個數組內的內容會替換占位符。上面的 SQL 語句執行的時候如下:

INSERT INTO user (user_name, age) VALUES ('Mark', 28)

第三個參數是一個回調函數,語句執行完成后會執行回調函數,函數的 err 參數可以獲取錯誤信息,函數的 this.changes 可以獲取受影響的行數,this.lastID 可以獲取 lastID 。

修改數據

修改數據還是用 run 方法,如下:

db.run('UPDATE user SET user_name = $newName WHERE user_name = $userName', {
  $userName: 'Mark',
  $newName: 'Jack'
}, function(err) {
  if (err) console.log(err);  // 如果有錯誤就輸出錯誤信息
  console.log(this.changes);  // 輸出受影響的行數
  console.log(this.lastID);  // 輸出 lastID
});

這里第二個參數是一個對象,對象的值會替換 SQL 語句中和屬性名相同的占位符,上面的語句執行的時候如下:

UPDATE user SET user_name = 'Jack' WHERE user_name = 'Mark'

查詢數據

刪除數據還是用 run 方法,和上面差不多,只是 SQL 語句不一樣,這里就不寫了。

查詢用的表內容如下:

id user_name age
1 Alice 30
2 Steve 26

下面查詢出上面表格中的所有內容:

db.all('SELECT id, user_name, age FROM user', (err, rows) => {
  if (err) console.log(err);  // 如果出現錯誤就輸出錯誤信息
  console.log(rows);  // 輸出查詢結果
});

查詢出的結果如下:

[
  { id: 1, user_name: 'Alice', age: 30 },
  { id: 2, user_name: 'Steve', age: 26 }
]

下面只查詢 user_name 為 Steve 的數據:

db.all('SELECT id, user_name, age FROM user WHERE user_name = ?', ['Steve'], (err, rows) => {
  if (err) console.log(err);  // 如果出現錯誤就輸出錯誤信息
  console.log(rows);  // 輸出查詢結果
});

這里的占位符還是和上面的一樣。

all 方法可以查詢多條數據,第一個參數就是 SQL 語句,后面的參數可以是用來替換占位符的內容,也可以是回調函數,回調函數需要放在最后?;卣{函數可以接收 err 和 rows 兩個參數,err 就是錯誤信息,rows 是查詢結果的數組,如果沒有查詢出內容 rows 就是一個空數組。

如果你只需要查詢一條數據,也就是查詢出的數據不會超過一條的話,可以考慮使用 get 方法,get 方法只會查詢一條數據,如下:

db.get('SELECT id, user_name, age FROM user', (err, row) => {
  if (err) console.log(err);
  console.log(row);
});

查詢結果如下:

{ id: 1, user_name: 'Alice', age: 30 }

雖然上面的表格中有兩條數據,但 get 方法只查詢出一條。

get 方法的參數和 all 差不多,第一個參數是 SQL 語句,后面的參數可以是用來替換 SQL 中的占位符的內容,也可以是一個回調函數,回調函數需要在最后。函數可以接收 err 和 row ,err 是錯誤信息,row 是查詢結果,如果沒有查詢出數據 row 就是 undefined 。