egg 項目實戰(七)Egg.js 連接 mysql 數據庫


1.創建 mysql 表結構

create database egg_article;

use egg_article;

create table article(
  id int(10) not null auto_increment,
  img text default null comment '縮略圖',
  title varchar(80) default null comment '文章標題',
  summary varchar(300) default null comment '文章簡介',
  content text default null comment '文章內容',
  createTime timestamp default null comment '發布時間',
  primary key(id)
)engine=InnoDB AUTO_INCREMENT=1 comment '文章表';

insert into article(img, title, summary, content, createTime)
values('編程必備基礎知識 計算機組成原理+操作系統+計算機網絡', 'https://img2.mukewang.com/szimg/5d1032ab08719e0906000338.jpg', '介紹編輯必備基礎知識', '快速、系統補足必備的計算機系統知識、更快更有趣、更貼近實際工作,讓你更快地學到滿足實際工作需要的知識,為以后的工作打好良好的基礎', '2020-03-03 10:20:20');

2.安裝 egg-mysql

mkdir server

cd server

npm init egg --type=simple

yarn add egg-mysql

3.配置 plugin.js

config/plugin.js

'use strict';

exports.mysql = {
  enable: true,
  package: 'egg-mysql',
};

4.配置 config.default.js

config/config.default.js

config.mysql = {
  // 單數據庫信息配置
  client: {
    // host
    host: 'localhost',
    // 端口號
    port: '3306',
    // 用戶名
    user: 'root',
    // 密碼
    password: 'root',
    // 數據庫名
    database: 'egg_article',    
  },
  // 是否加載到 app 上,默認開啟
  app: true,
  // 是否加載到 agent 上,默認關閉
  agent: false,
};

5.調用

async index() {
  const { ctx, app } = this;
  const res = await app.mysql.select('article');
  console.log(res);
  ctx.body = 'hi, egg';
}

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM