xorm使用说明(PostgreSQL)

参考: http://gobook.io/read/github.com/go-xorm/manual-en-US/

安装

go get github.com/go-xorm/xorm
go get github.com/lib/pq

使用

Create ORM Engine

package main
import (
    _ "github.com/lib/pq"
    "github.com/go-xorm/xorm"
    "fmt"
)

const (
  host     = "localhost"
  port     = 5432
  user     = "test"
  password = "test"
  dbname   = "blogbase"
)

var engine *xorm.Engine

func main() {
    var err error
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
    "password=%s dbname=%s sslmode=disable",
    host, port, user, password, dbname)
    engine, err = xorm.NewEngine("postgres", psqlInfo)
    if err != nil {
        println(err.Error())
        return
    }
    ## 设置日志
    f, err1 := os.Create("sql.log")
    if err1 != nil {
        println(err1.Error())
        return
    }
    engine.SetLogger(xorm.NewSimpleLogger(f))
}

设置连接池参数(Connections pool)

  • Use engine.SetMaxIdleConns() to set idle connections.
  • Use engine.SetMaxOpenConns() to set Max connections. This methods support only Go 1.2+.
  • Use engine.SetConnMaxLifetime() to set Max life time. This methods support only Go 1.6+.

define a struct

名字映射规则 name mapping rule

三种规则:

  • SnakeMapper:如果有大写字母,就在大写字母之间插入’_’, 并把大写字母改为小写,比如 ID,改为’i_d’, xorm默认使用这种模式
  • SameMapper: 保持不变
  • GonicMapper: 把大写字母改为小写,比如ID改为’id’

设置规则

engine.SetMapper(core.SameMapper{})

表名和规则名可以使用不同的规则

engine.SetTableMapper(core.SameMapper{})
engine.SetColumnMapper(core.SnakeMapper{})

列类型映射

go type’s kind value method xorm type
implemented Conversion Conversion.ToDB / Conversion.FromDB Text
int, int8, int16, int32, uint, uint8, uint16, uint32 Int
int64, uint64 BigInt
float32 Float
float64 Double
complex64, complex128 json.Marshal / json.UnMarshal Varchar(64)
[]uint8 Blob
array, slice, map except []uint8 json.Marshal / json.UnMarshal Text
bool 1 or 0 Bool
string Varchar(255)
time.Time DateTime
cascade struct primary key field value BigInt
struct json.Marshal / json.UnMarshal Text
Others Text

你可能感兴趣的:(编程技巧)