使用 Sequelize 在 NodeJS 中建立 MySQL 表


Sequelize 簡介

Sequelize 是一個基於 Promise 的 Node.js ORM,支援多種資料庫,例如 Postgres、MySQL、MariaDB、SQLite 和 Microsoft SQL Server。

以下是 NodeJS Sequelize 的一些主要功能:

  • 事務支援

  • 關係

  • 急切載入和延遲載入

  • 讀取複製等等…

使用 Sequelize 連線 MySQL

  • 我們需要使用 Sequelize 建立 MySQL 和 Node.js 之間的連線。

  • 成功連線到 sequelize 後,我們需要以下三個檔案進行配置。請仔細地僅在各自的資料夾中建立以下檔案。

    • SequelizeDemo > application.js

      這是我們的根檔案,它將包含實際邏輯。

    • SequelizeDemo>utils>database.js

      這將包含連線到 MySQL 的所有詳細資訊。

    • SequelizeDemo>models>user.js

      這將包含所需的模型資訊。

示例

配置 Database.js

const Sequelize = require('sequelize')
const sequelize = new Sequelize(
   'YOUR_DB_NAME', // TutorialsPoint
   'YOUR_DB_USER_NAME', // root
   'YOUR_DB_PASSWORD', //root{
      dialect: 'mysql',
      host: 'localhost'
   }
);
module.exports = sequelize

請填寫所有連線到資料庫的輸入。

配置 User.js

使用此檔案定義模型和表之間的對映。

const Sequelize = require('sequelize')
const sequelize = require('../utils/database')
const User = sequelize.define('user', {
   // Name of Column #1 and its properties defined: id
   user_id:{

      // Integer Datatype
      type:Sequelize.INTEGER,

      // Increment the value automatically
      autoIncrement:true,

      // user_id can not be null.
      allowNull:false,

      // To uniquely identify user
      primaryKey:true
   },

   // Name of Column #2: name
   name: { type: Sequelize.STRING, allowNull:false },

   // Name of Column #3: email
   email: { type: Sequelize.STRING, allowNull:false },

   // Column: Timestamps
   createdAt: Sequelize.DATE,
   updatedAt: Sequelize.DATE,
})
module.exports = User

配置 app.js

要建立模型,我們可以使用兩種方法中的一種:

  • **sync() 方法** - 僅在模型存在時建立模型。如果模型存在,則不會覆蓋模型。

  • **sync({force: true}) 方法** - 如果模型不存在,則會建立一個新模型;但是,如果模型存在,則會覆蓋現有模型。

// Importing the database model
const sequelize = require('./database')

// Importing the user model
const User = require('./user')

// Creating all the tables defined in user
sequelize.sync()

// You can change the user.js file
// And run this code to check if it overwrites the existing code.
sequelize.sync({force:true)

輸出

執行上述程式後,您將獲得以下輸出:

C:\Users\SequelizeDemo>> node app.js
Executing (default): CREATE TABLE IF NOT EXISTS `users` (`user_id` INTEGER NOT NULL auto_increment , `name` VARCHAR(255) NOT NULL, `email` VARCHAR(255) NOT NULL, `createdAt` DATETIME, `updatedAt` DATETIME, PRIMARY KEY (`user_id`)) ENGINE=InnoDB;
Executing (default): SHOW INDEX FROM `users`

現在,您可以檢查您的資料庫。上面應該已經建立了該表。

更新於:2021年4月27日

2K+ 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.