Go语言 使用Beego ORM框架 连接MySql生成Api接口项目

  数据库创建表脚本

/*
 Navicat Premium Data Transfer

 Source Server         : mysql_localhost
 Source Server Type    : MySQL
 Source Server Version : 50728
 Source Host           : localhost:3306
 Source Schema         : business

 Target Server Type    : MySQL
 Target Server Version : 50728
 File Encoding         : 65001


*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(36) NOT NULL AUTO_INCREMENT,
  `stu_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `createtime` datetime(6) NULL DEFAULT CURRENT_TIMESTAMP(6),
  `updatetime` datetime(6) NULL DEFAULT CURRENT_TIMESTAMP(6),
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (2, 'lisi', '2020-03-27 17:12:37.992956', '2020-03-27 17:12:37.993035');
INSERT INTO `student` VALUES (3, 'zhangsan', '2020-03-27 16:41:05.665304', '2020-03-27 16:59:10.643557');

SET FOREIGN_KEY_CHECKS = 1;
  • 连接MySql需要下载驱动,使用命令执行
    go get github.com/go-sql-driver/mysql
  • ORM框架,安装beego框架时,已经安装了,这里不需要再次安装,使用如下命令生成项目
bee api business-api -conn="root:root@tcp(127.0.0.1:3306)/business"

  business-api:项目名称,conn中的参数,第一个root为用户名,第二个为密码,127.0.0.1代表本机,3306为数据库端口,business为MySql下的数据库

  • 生成好的项目结构如下:

  • 首次运行时,执行如下命令,生成swagger接口文档
bee run -gendoc=true -downdoc=true

原文地址:https://www.cnblogs.com/personblog/p/12666947.html