用go xorm来操作mysql

       很有用,来看下:

package main

import (
    "fmt"
    "github.com/go-xorm/xorm"
    "github.com/go-xorm/core"
    _ "github.com/go-sql-driver/mysql"
)

// 对应数据库的tablename必须为student
// 执行mysql时,对应的字段为xxx,yyy,zzz; 也可以省掉,默认的mysql字段为id,username,address
type Student struct {
    Id       int       `xorm:"INT(11) 'xxx'"`
    Username string    `xorm:"VARCHAR(64) 'yyy'"`
    Address  string    `xorm:"VARCHAR(256) 'zzz'"`
}

func main()  {
    engine, err := xorm.NewEngine("mysql", "root@/taoge?charset=utf8")  // dbname是taoge
    if err != nil{
        fmt.Println(err)
        return
    }

    // 如下Ping可以不要
    // if err := engine.Ping(); err != nil{
    //     fmt.Println(err)
    //     return
    // }

    //engine.ShowSQL(true)  // 显示SQL的执行, 便于调试分析
    engine.SetTableMapper(core.SnakeMapper{})

    st1 := new(Student)
    st1.Username = "taoge"
    st1.Address = "China"
    affected, err := engine.Insert(st1)
    fmt.Println(affected)

    st2 := new(Student)
    result,err := engine.Where("xxx=?", 1).Get(st2)
    fmt.Println(result)

    fmt.Println(st2.Username)
    fmt.Println(st2.Address)
}

        创建数据库:

CREATE TABLE `student` (
  `xxx` int(11) NOT NULL AUTO_INCREMENT,
  `yyy` varchar(64) NOT NULL,
  `zzz` varchar(256) NOT NULL ,
  PRIMARY KEY (`xxx`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

       运行结果:

1
true
taoge
China

 

      不多说。

 

你可能感兴趣的:(s4:,数据库,S1:,Go,s2:,软件进阶,s2:,后台开发)