開始使用
在本教學中,您將學習如何簡單設定 Sequelize。
安裝
Sequelize 可透過 npm (或 yarn) 取得。
npm install --save sequelize
您還必須手動安裝您選擇的資料庫驅動程式
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
$ npm install --save oracledb # Oracle Database
連線到資料庫
要連線到資料庫,您必須建立一個 Sequelize 實例。這可以透過將連線參數個別傳遞給 Sequelize 建構函式,或傳遞單一連線 URI 來完成
const { Sequelize } = require('sequelize');
// Option 1: Passing a connection URI
const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite
const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname') // Example for postgres
// Option 2: Passing parameters separately (sqlite)
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
// Option 3: Passing parameters separately (other dialects)
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
});
Sequelize 建構函式接受許多選項。它們記錄在API 參考中。
測試連線
您可以使用 .authenticate()
函式來測試連線是否正常
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
關閉連線
Sequelize 預設會保持連線開啟,並將相同的連線用於所有查詢。如果您需要關閉連線,請呼叫 sequelize.close()
(它是非同步的並返回 Promise)。
一旦呼叫 sequelize.close()
,就無法開啟新的連線。您將需要建立新的 Sequelize 實例才能再次存取您的資料庫。
術語慣例
請注意,在上面的範例中,Sequelize
指的是程式庫本身,而 sequelize
指的是 Sequelize 的實例,它代表與一個資料庫的連線。這是建議的慣例,並且將在整個文件中遵循。
閱讀文件的提示
建議您在閱讀 Sequelize 文件時在本地執行程式碼範例。這將幫助您更快地學習。最簡單的方法是使用 SQLite 方言
const { Sequelize, Op, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
// Code here! It works!
若要實驗其他較難在本地設定的方言,您可以使用 Sequelize SSCCE GitHub 儲存庫,它允許您直接從 GitHub 在所有支援的方言上執行程式碼,免費且無需任何設定!
新資料庫與現有資料庫
如果您從頭開始一個專案,並且您的資料庫仍然是空的,則可以從一開始就使用 Sequelize,以便自動化建立資料庫中的每個表格。
此外,如果您想使用 Sequelize 連線到已經填滿表格和資料的資料庫,這也行得通!Sequelize 在這兩種情況下都能滿足您的需求。
記錄
預設情況下,Sequelize 會針對執行的每個 SQL 查詢記錄到主控台。options.logging
選項可用於自訂此行為,方法是定義每次 Sequelize 記錄某些內容時執行的函式。預設值是 console.log
,當使用它時,只會顯示記錄函式呼叫的第一個記錄參數。例如,對於查詢記錄,第一個參數是原始查詢,第二個參數(預設情況下隱藏)是 Sequelize 物件。
options.logging
的常見有用值
const sequelize = new Sequelize('sqlite::memory:', {
// Choose one of the logging options
logging: console.log, // Default, displays the first parameter of the log function call
logging: (...msg) => console.log(msg), // Displays all log function call parameters
logging: false, // Disables logging
logging: msg => logger.debug(msg), // Use custom logger (e.g. Winston or Bunyan), displays the first parameter
logging: logger.debug.bind(logger), // Alternative way to use custom logger, displays all messages
});
Promise 與 async/await
Sequelize 提供的大部分方法都是非同步的,因此會返回 Promise。它們都是 Promise,因此您可以開箱即用地使用 Promise API(例如,使用 then
、catch
、finally
)。
當然,使用 async
和 await
也沒問題。