golang学习之beego增删改查代码实现

记录下使用beego的增删改查实现,数据库使用mysql,完整代码如下:

package main

import (
    _ "crud_beego/routers" //自动注册路由
    "fmt"
    "github.com/astaxie/beego"
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
)

const (
    DRIVER_NAME   = "mysql"
    DATA_SOURCE   = "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8&loc=Asia%2FShanghai"
    MAX_IDLE_CONN = 5
    MAX_OPEN_CONN = 30
)

type User struct {
    Id       int
    Name     string
    Email    string
    Age      int
    isActive bool
}

func (u *User) TableName() string {
    return "t_user"
}

func registerDB() {
    orm.Debug = true
    orm.RegisterDataBase("default", DRIVER_NAME, DATA_SOURCE, MAX_IDLE_CONN, MAX_OPEN_CONN)
    orm.RegisterModel(new(User))
}

func (this User) ToString() string {
    return fmt.Sprintf("Id:%d\tName:%s\tEmail:%s\tAge:%d\tisActive:%v", this.Id, this.Name, this.Email, this.Age, this.isActive)
}

func createUsers() {
    users := []User{
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
        User{Name: "adadmin1", Email: "14199@111.com", Age: 12},
    }
    o := orm.NewOrm()
    if successNums, err := o.InsertMulti(len(users), users); err != nil {
        fmt.Println("insert fail.....")
    } else {
        fmt.Println("success inserted %d datas", successNums)
    }
}

//find all users
func listUsers() {
    var users []User
    orm.NewOrm().QueryTable("t_user").All(&users)
    for _, user := range users {
        fmt.Println(user.ToString())
    }
}

//get user count
func countUser() {
    cnt, _ := orm.NewOrm().QueryTable("t_user").Count()
    fmt.Println("All user count:", cnt)
}

//get the only one user
func getUser() {
    var user User
    err := orm.NewOrm().QueryTable("t_user").Filter("Id", 5).One(&user)
    if err == nil {
        fmt.Println(user.ToString())
    }
}

//get the only one user
func getUsers() {
    var users []User
    _, err := orm.NewOrm().QueryTable("t_user").Filter("name__contains", "awd").All(&users)
    if err == nil {
        for _, user := range users {
            fmt.Println(user.ToString())
        }
    }
}

//get limit user
func limitUser() {
    var users []User
    _, err := orm.NewOrm().QueryTable("t_user").Limit(6).OrderBy("-Name").All(&users)
    if err == nil {
        for _, user := range users {
            fmt.Println(user.ToString())
        }
    }
}

//get user limit,offset
func limitoffsetUser() {
    var users []User
    _, err := orm.NewOrm().QueryTable("t_user").Limit(1, 4).OrderBy("Id").All(&users)
    if err == nil {
        for _, user := range users {
            fmt.Println(user.ToString())
        }
    }
}

//del user
func delUser() {
    num, err := orm.NewOrm().QueryTable("t_user").Filter("Id", "5").Delete()
    fmt.Printf("Affected Num: %s, %s", num, err)
}

//update user
func updateUser() {
    num, err := orm.NewOrm().QueryTable("t_user").Filter("name__contains", "awd").Update(orm.Params{
        "name": "#########",
    })
    fmt.Printf("Affected Num: %s, %s", num, err)
}

func main() {
    registerDB()
    createUsers()
    listUsers()
    countUser()
    getUser()
    getUsers()
    limitoffsetUser()
    delUser()
    updateUser()
    beego.Run()
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏木宛城主

Fix SharePoint 2013 Site in Read only mode after an interrupted backup

Problem When I was backing up SharePoint Site Collection Automatically with Powe...

2418
来自专栏技术小黑屋

Package Stopped State Since Android 3.1

Since Android 3.1, Android has introduced a LaunchControl mechanism. It’s call S...

1041
来自专栏Android 开发学习

Android studio 2.2 JNI ffmpeg 简单的播放器(这里只有视频解码)include "libavcodec/avcodec.h"include "libavformat/avf

5053
来自专栏c#开发者

How to pass multiple values from child widow

In my previous post which was relating to implementing dialog box in web based a...

3688
来自专栏H2Cloud

Tips for thrift

Introduction I have designed and developed game servers successfully with thrift...

3645
来自专栏大数据学习笔记

Hadoop基础教程-第10章 HBase:Hadoop数据库(10.7 HBase 批量导入)

第10章 HBase:Hadoop数据库 10.7 HBase 批量导入 10.7.1 批量导入数据的方法 向HBase表中导入一条数据可以使用HBase Sh...

2435
来自专栏Golang语言社区

在GO中编写一个简单的shell

In this post, we will write a minimalistic shell for UNIX(-like) operating syste...

1405
来自专栏Golang语言社区

Go调试简单的内存泄漏

Memory leaks are a class of bugs where memory is not released even after it is n...

5313
来自专栏全栈架构

Spring Boot 与 Kotlin 上传文件

如果我们做一个小型的web站,而且刚好选择的kotlin 和Spring Boot技术栈,那么上传文件的必不可少了,当然,如果你做一个中大型的web站,那建议你...

1113
来自专栏大数据学习笔记

Elasticsearch 5.x 安装与配置

Elasticsearch官方建议使用 Oracle的JDK8 1、下载安装 [root@vnode0 opt]# tar -zxvf elasticsearc...

4428

扫码关注云+社区

领取腾讯云代金券