node.js使用Sequelize操作數(shù)據(jù)庫(kù)
Sequelize是一個(gè)基于 promise 的 Node.js ORM(對(duì)象關(guān)系映射)。
目前支持 Postgres、MySQL、MariaDB、SQLite和Microsoft SQL Server;?它具有強(qiáng)大的事務(wù)支持, 關(guān)聯(lián)關(guān)系, 預(yù)讀和延遲加載,讀取復(fù)制等功能。
官方網(wǎng)址:
https://sequelize.org/v5/index.html
npm安裝:npm install --save sequelize
使用何種數(shù)據(jù)庫(kù),要安裝對(duì)應(yīng)的npm類庫(kù),對(duì)應(yīng)的幾類數(shù)據(jù)庫(kù)安裝:

數(shù)據(jù)庫(kù)的初始化代碼:
const Sequelize = require('sequelize');
//第一種方式:傳遞數(shù)據(jù)庫(kù)連接信息(ip、端口、用戶名密碼等)
sequelize = new Sequelize('database', 'username', 'password',{host: 'localhost',?dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */});
//第二種方式:使用uri的字符串連接方式
sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
驗(yàn)證數(shù)據(jù)庫(kù)連接是否成功:
sequelize.authenticate().then(() => {?? ? ?console.log('Connection has been established successfully.');
}).catch(err => {console.error('Unable to connect to the database:', err);});
// await方式:
???await?sequelize.authenticate();
數(shù)據(jù)庫(kù)的操作上,只要是以模型和數(shù)據(jù)庫(kù)的表進(jìn)行對(duì)應(yīng),同時(shí)也支持sql語句的查詢方式。
模型定義(https://sequelize.org/v5/manual/models-definition.html):
const Model = Sequelize.Model;
class User extends Model {}
User.init({
//屬性設(shè)置 ??
? firstName: { ?type: Sequelize.STRING, ?allowNull: false ? }, ? ??
?lastName: { ? ? ? type: Sequelize.STRING ? ??}}, {?
//屬性設(shè)置 ?
? sequelize, ? modelName: 'user' ??});
需要注意的是,上述定義一個(gè)user的模型,需要對(duì)應(yīng)在數(shù)據(jù)庫(kù)表中,有users這個(gè)表,要實(shí)現(xiàn)自己定義表名,需要在屬性中設(shè)置以下兩個(gè)參數(shù):
freezeTableName:?false,
tableName:?'define_user'
直接執(zhí)行sql語句查詢(https://sequelize.org/v5/manual/raw-queries.html):
sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT}) ?.then(users => { ? ?//返回json對(duì)象 ?})
參考文檔:
官網(wǎng):
https://sequelize.org/v5/index.html
中文文檔網(wǎng)站:
https://github.com/demopark/sequelize-docs-Zh-CN