1. 程式人生 > 程式設計 >node.js通過Sequelize 連線MySQL的方法

node.js通過Sequelize 連線MySQL的方法

一.通過koa2腳手架構建專案

1.1 安裝koa-generator
在終端輸入:

$ npm install -g koa-generator

1.2 使用koa-generator生成koa2專案

$ koa2 HelloKoa2

成功建立專案後,進入專案目錄,並執行npm install命令

$ cd HelloKoa2 
$ npm install

1.3 啟動專案
在終端輸入:

$ npm start

專案啟動後,預設埠號是3000,在瀏覽器中執行可以得到下圖的效果說明執行成功。

二.建立連線

2.1剛剛建立的檔案使用webstorm開啟
新建一個db目錄

在這裡插入圖片描述

2.2檢視Sequelize文件


使用npm安裝Sequelize

npm install --save sequelize

你還必須手動為所選資料庫安裝驅動程式選擇一個方法之一:

# 選擇以下之一:
$ 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

我這裡下載得是MySQL2

2.3連線資料庫
再剛剛建立得db檔案加里面新增**config.js**


新增連線程式碼:

module.exports = {
 dbsMysql: 'mysql://root:123456@localhost:3306/new'
 //root是資料庫管理員賬號,‘123546'是密碼 3306是埠號(MySQL預設是3306) school_admin是資料庫名稱

}

繼續在db資料夾裡面新增mysql.js
新增連線以及新增日記:

const Sequelize = require('sequelize');
const mysqlurl = require('./config').dbsMysql
const sequelize = new Sequelize(mysqlurl,{
 // 選擇一種日誌記錄引數
 logging: console.log // 預設值,顯示日誌函式呼叫的第一個引數
});
// //每次啟動server重新整理資料庫
//  (async ()=>{
//   await sequelize.sync({ force: true });
//  })()

module.exports = sequelize

三.建立模型

3.1模型定義
在db目錄下新增models資料夾再新增一個new2.js
定義模型:

const { Sequelize,DataTypes,Model } = require('sequelize');
const sequelize = require('../mysql');

const new2 = sequelize.define('t_new2',{
  name: {
   type: DataTypes.STRING,allowNull: false
  },},{
  // 這是其他模型引數
  freezeTableName: true
 });
// 定義的模型是類本身
module.exports= new2

四.新增路由

4.1建立new2路由
在routes資料夾中新增new2.js

//引入kob得routes模組
const router = require('koa-router')()
//定義模型為剛剛建立得new2.js
let Model = require("../db/models/new2");
//正常來說啟動埠為http://localhost:3000 新增/new2就可以進入new2路由
router.prefix('/new1')
// 進入new2路由以後可以列印this is a users response!
router.get('/',function (ctx,next) {
 ctx.body = 'this is a users response!'

})
//設定增加add介面
router.post('/add',async function (ctx,next) {
 console.log(ctx.request.body)
 const new2 = await Model.create(ctx.request.body);
 ctx.body = {
  code:200,data:new2
 }
})
//設定查詢find介面
router.post('/find',next) {
 const new2 =await Model.findAll({include: []})
 console.log(1111)
 ctx.body = {
  code: 200,data: new2
 }
})
//設定通過id得到所需資訊的get介面
router.post('/get',next) {
 // let users = await User.
 // find({})
 console.log(ctx.request.body)


 let new2 = await Model.findOne({
  // attributes: ['name','where']
  where: {
   id: ctx.request.body.id
  }
 });
 ctx.body = {
  code:200,data:new2
 }
})
//設定修改update介面
router.post('/update',next) {
 console.log(ctx.request.body)
 // let pbj = await Model.update({ _id: ctx.request.body._id },ctx.request.body);

 let new2 = await Model.update(ctx.request.body,{
  where: {
   id: ctx.request.body.id
  }
 });
 ctx.body = new2
})
//設定刪除delete介面
router.post('/delete',next) {
 console.log(ctx.request.body)
 // 刪除所有名為 "Jane" 的人
 await Model.destroy({
  where: { id: ctx.request.body.id }
 });
 ctx.body = 'shibai '
})

// //每次啟動server重新整理資料庫
//  (async ()=>{
//   await sequelize.sync({ force: true });
//  })()
module.exports = router

4.2在app.js裡面新增路由

在
在這裡插入圖片描述

//引入剛剛建立的new2路由
const new2 =require('./routes/new2')
//使用我們的路由
app.use(new2.routes(),new2.allowedMethods())

4.3啟動專案

在這裡插入圖片描述

在資料庫中檢視

在這裡插入圖片描述

5.測試

5.1使用瀏覽器檢視

輸入url:http://localhost:3000/new2

在這裡插入圖片描述

5.2.使用postman測試介面
測試find介面(因為我們寫的find方法使用的post方法所以記得將get換成post):

http://localhost:3000/new2/find

在這裡插入圖片描述

測試get介面

在這裡插入圖片描述

展示一下最後的目錄

在這裡插入圖片描述

到此這篇關於node.js通過Sequelize 連線MySQL的文章就介紹到這了,更多相關node.js連線MySQL內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!