go iris xorm包使用(sqlite3数据库增删查改) 测试一下robotgo自动化操作,顺便解决了原来的mingw版本中只有gcc,没有g++的问题

官网https://studyiris.com/example/orm/xorm.html例子,稍做修改

1、我是win64,但没有遇到mingw问题,应该是之前安装过gcc环境,参考:测试一下robotgo自动化操作,顺便解决了原来的mingw版本中只有gcc,没有g++的问题

2、将其中的字段名、字段内容改为中文,并按id访问数据表中的行,没遇到乱码问题,很好。

代码如下:

//包主显示如何在您的Web应用程序中使用orm
//它只是插入一列并选择第一列。
package main

import (
    "time"

    "github.com/go-xorm/xorm"
    "github.com/kataras/iris"
    _ "github.com/mattn/go-sqlite3"
)

/*
   go get -u github.com/mattn/go-sqlite3
   go get -u github.com/go-xorm/xorm
   如果您使用的是win64并且无法安装go-sqlite3:
       1.下载:https://sourceforge.net/projects/mingw-w64/files/latest/download
       2.选择“x86_x64”和“posix”
       3.添加C:\Program Files\mingw-w64\x86_64-7.1.0-posix-seh-rt_v5-rev1\mingw64\bin
       到你的PATH env变量。
   手册: http://xorm.io/docs/
*/
//User是我们的用户表结构。
type User struct {
    ID        int64  // xorm默认自动递增
    Version   string `xorm:"varchar(200)"`
    Salt      string
    A用户名      string
    Password  string    `xorm:"varchar(200)"`
    Languages string    `xorm:"varchar(200)"`
    CreatedAt time.Time `xorm:"created"`
    UpdatedAt time.Time `xorm:"updated"`
}

func main() {
    app := iris.New()
    orm, err := xorm.NewEngine("sqlite3", "./test.db")
    if err != nil {
        app.Logger().Fatalf("orm failed to initialized: %v", err)
    }
    iris.RegisterOnInterrupt(func() {
        orm.Close()
    })
    err = orm.Sync2(new(User))
    if err != nil {
        app.Logger().Fatalf("orm failed to initialized User table: %v", err)
    }
    app.Get("/insert", func(ctx iris.Context) {
        user := &User{A用户名: "大大", Salt: "hash---", Password: "hashed", CreatedAt: time.Now(), UpdatedAt: time.Now()}
        orm.Insert(user)
        ctx.Writef("user inserted: %#v", user)
    })
    app.Get("/get/{id:int}", func(ctx iris.Context) {
        id, _ := ctx.Params().GetInt("id")
        //int到int64
        id64 := int64(id)
        ctx.Writef("id is %#v", id64)
        user := User{ID: id64}
        if ok, _ := orm.Get(&user); ok {
            ctx.Writef("user found: %#v", user)
        }
    })
    app.Get("/delete", func(ctx iris.Context) {
        user := User{ID: 1}
        orm.Delete(user)
        ctx.Writef("user delete: %#v", user)
    })
    app.Get("/update", func(ctx iris.Context) {
        user := User{ID: 2, A用户名: "小小"}
        orm.Update(user)
        ctx.Writef("user update: %#v", user)
    })
    // http://localhost:8080/insert
    // http://localhost:8080/get/数字
    app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}

增:先访问2次:http://localhost:8080/insert

查:http://localhost:8080/get/1 和 http://localhost:8080/get/2

删:http://localhost:8080/delete

改:http://localhost:8080/update

猜你喜欢

转载自www.cnblogs.com/pu369/p/10797723.html