Node 操作 MySQL 數據庫

1项棠、安裝

Linux 版

Linux下安裝mysql

Mac 版

2雕凹、使用 Sequelize

一般會有兩個依賴: mysql2 驅動和 Sequelize ORM 框架

const Sequelize = require("sequelize");
const config = require("./config");

// 第一步:建立 ORM 連接
var sequelize = new Sequelize(
  config.database,
  config.username,
  config.password,
  {
    host: config.host,
    dialect: "mysql",
    pool: {
      max: 5,
      min: 0,
      idle: 30000
    }
  }
);

// 第二步:建立 Model
var Pet = sequelize.define(
  "pet",
  {
    id: {
      type: Sequelize.STRING(50),
      primaryKey: true
    },
    name: Sequelize.STRING(100),
    gender: Sequelize.BOOLEAN,
    birth: Sequelize.STRING(10),
    createdAt: Sequelize.BIGINT,
    updatedAt: Sequelize.BIGINT,
    version: Sequelize.BIGINT
  },
  {
    timestamps: false
  }
);

var now = Date.now();
// 第三步:利用 Model 創(chuàng)建實例
Pet.create({
  id: "g-" + now,
  name: "Gaffey",
  gender: false,
  birth: "2007-07-07",
  createdAt: now,
  updatedAt: now,
  version: 0
})
  .then(function(p) {
    console.log("created." + JSON.stringify(p));
  })
  .catch(function(err) {
    console.log("failed: " + err);
  });
// 查詢操作 findAll
(async () => {
  var pets = await Pet.findAll({
    where: {
      name: "Gaffey"
    }
  });
  console.log(`find ${pets.length} pets:`);
  for (let p of pets) {
    console.log(JSON.stringify(p));
  }
})();
// 更新操作 save
(async () => {
    var p = await queryFromSomewhere();
    p.gender = true;
    p.updatedAt = Date.now();
    p.version ++;
    await p.save();
})();
// 刪除操作
(async () => {
    var p = await queryFromSomewhere();
    await p.destroy();
})()

使用Sequelize操作數據庫的一般步驟就是:

1引镊、首先骂因,通過某個Model對象的findAll()方法獲取實例哭靖;
2砖茸、如果要更新實例侣诵,先對實例屬性賦新值希坚,再調用save()方法边苹;
3、如果要刪除實例裁僧,直接調用destroy()方法个束。

注意findAll()方法可以接收where慕购、order這些參數,這和將要生成的SQL語句是對應的茬底。

3沪悲、使用 sequelize-cli

方便快速創(chuàng)建數據庫

npm i sequelize-cli -D
npm i sequelize
npm i mysql2

配置.sequelizerc,如果不配置的話阱表,sequelize init 初始化的文件夾會出現在項目根目錄下面殿如,如果配置了.sequelizerc 就可以指定到相應的目錄

const path = require('path')
module.exports = {
    'config': path.resolve('./app','config.json'),
    'migrations-path': path.resolve('./app','migrations'),
    'models-path': path.resolve('./app','models'),
    'seeders-path': path.resolve('./app','seeders'),
}

在項目根目錄下執(zhí)行

npx sequelize init
  • 創(chuàng)建 migrations(定義如何創(chuàng)建表)
npx sequelize migration:create --name create-shops-table

// xxxxxxxxx-create-shops-table.js
module.exports = {
  up: (queryInterface, Sequelize) => queryInterface.createTable(
    'shops',
    {
      id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      thumb_url: Sequelize.STRING,
      created_at: Sequelize.DATE,
      updated_at: Sequelize.DATE,
    },
  ),

  down: queryInterface => queryInterface.dropTable('shops'),
};
  • 追加字段
npx sequelize migration:create --name add-columns-to-shops-table
// add-columns-to-shops-table.js
module.exports = {
  up: (queryInterface, Sequelize) => Promise.all([
    queryInterface.addColumn('shops', 'address', { type: Sequelize.STRING }),
  ]),

  down: queryInterface => Promise.all([
    queryInterface.removeColumn('shops', 'address'),
  ]),
};
  • 執(zhí)行 migrations(創(chuàng)建/撤銷表)
npx sequelize db:migrate
  • 創(chuàng)建seed(初始化數據)
npx sequelize seed:create --name init-shops

// seeders/xxxxxxxxx-init-shops.js

const timestamps = {
  created_at: new Date(),
  updated_at: new Date(),
};

module.exports = {
  up: queryInterface => queryInterface.bulkInsert(
    'shops',
    [
      { id: 1, name: '店鋪1', thumb_url: '1.png', ...timestamps },
      { id: 2, name: '店鋪2', thumb_url: '2.png', ...timestamps },
      { id: 3, name: '店鋪3', thumb_url: '3.png', ...timestamps },
      { id: 4, name: '店鋪4', thumb_url: '4.png', ...timestamps },
    ],
    {},
  ),

  down: (queryInterface, Sequelize) => {
    const { Op } = Sequelize;
    // 刪除 shop 表 id 為 1,2捶枢,3握截,4 的記錄
    return queryInterface.bulkDelete('shops', { id: { [Op.in]: [1, 2, 3, 4] } }, {});
  },
};
  • 執(zhí)行 seed
npx sequelize db:seed:all   // 使用所有 seed
npx sequelize db:seed --seed xxxxxxxxx-init-shopsjs   // 使用指定 seed
  • 創(chuàng)建model(與數據庫表結構做對應)
npx sequelize model:create  --name shops --attributes "name:string"

該命令會同時創(chuàng)建 models/shops.js 和 migrations/ xxx-create-shops.js,所以上述的migration命令用的不多烂叔,并且xxx-create-shops.js 會自動增加三個字段 id , createdAt , updatedAt

// models/shops.js
module.exports = (sequelize, DataTypes) => sequelize.define(
  'shops',
  {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    }
  },
  {
    tableName: 'shops',
  },
);
// migrations/xxx-create-shops.js
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('shops', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('shops');
  }
};

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末谨胞,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子蒜鸡,更是在濱河造成了極大的恐慌胯努,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逢防,死亡現場離奇詭異叶沛,居然都是意外死亡,警方通過查閱死者的電腦和手機忘朝,發(fā)現死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門灰署,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人局嘁,你說我怎么就攤上這事溉箕。” “怎么了悦昵?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵肴茄,是天一觀的道長。 經常有香客問我但指,道長寡痰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任棋凳,我火速辦了婚禮拦坠,結果婚禮上,老公的妹妹穿的比我還像新娘剩岳。我一直安慰自己贪婉,他們只是感情好,可當我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布卢肃。 她就那樣靜靜地躺著疲迂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪莫湘。 梳的紋絲不亂的頭發(fā)上尤蒿,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音幅垮,去河邊找鬼腰池。 笑死,一個胖子當著我的面吹牛忙芒,可吹牛的內容都是我干的示弓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼呵萨,長吁一口氣:“原來是場噩夢啊……” “哼奏属!你這毒婦竟也來了?” 一聲冷哼從身側響起潮峦,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤囱皿,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后忱嘹,有當地人在樹林里發(fā)現了一具尸體嘱腥,經...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年拘悦,在試婚紗的時候發(fā)現自己被綠了齿兔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡础米,死狀恐怖分苇,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情椭盏,我是刑警寧澤组砚,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站掏颊,受9級特大地震影響糟红,放射性物質發(fā)生泄漏。R本人自食惡果不足惜乌叶,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一盆偿、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧准浴,春花似錦事扭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽今野。三九已至,卻和暖如春罐农,著一層夾襖步出監(jiān)牢的瞬間条霜,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工涵亏, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留宰睡,地道東北人。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓气筋,卻偏偏與公主長得像拆内,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子宠默,可洞房花燭夜當晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內容