zoukankan      html  css  js  c++  java
  • 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';
    }

    .

  • 相关阅读:
    398. Random Pick Index
    739. Daily Temperatures
    779. K-th Symbol in Grammar
    698. Partition to K Equal Sum Subsets
    783. Minimum Distance Between BST Nodes
    asp.netcore 深入了解配置文件加载过程
    啥叫K8s?啥是k8s?
    Asp.NetCore轻松学-实现一个轻量级高可复用的RabbitMQ客户端
    Asp.Net Core 轻松学-一行代码搞定文件上传
    目录---Asp.NETCore轻松学系列【目录】
  • 原文地址:https://www.cnblogs.com/crazycode2/p/12422406.html
Copyright © 2011-2022 走看看