osm

package module
Version: v1.0.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2022 License: MIT Imports: 14 Imported by: 1

README

osm

osm(Object Sql Mapping And Template)是用go编写的ORM工具,目前已在生产环境中使用,只支持mysql和postgresql(其他数据库没有测试过)。

以前是使用MyBatis开发java服务端,它的sql mapping很灵活,把sql独立出来,程序通过输入与输出来完成所有的数据库操作。

osm就是对MyBatis的简单模仿。当然动态sql的生成是使用go和template包,所以sql mapping的格式与MyBatis的不同。sql xml 格式如下:

<?xml version="1.0" encoding="utf-8"?>
<osm>
 <select id="selectUsers" result="structs">
   SELECT id,email
   FROM user
   {{if ne .Email ""}} where email=#{Email} {{end}}
   order by id
 </select>
</osm>

osm获取

go get github.com/yinshuwei/osm

api doc

http://godoc.org/github.com/yinshuwei/osm

Quickstart

创建数据库

create database test;
use test;

创建user表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) DEFAULT NULL,
  `nickname` varchar(45) DEFAULT NULL,
  `create_time` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='user table';
  • 直接执行SQL(不支持go template解析)示例

example_sql.go

package main

import (
    "fmt"
    "time"

    _ "github.com/go-sql-driver/mysql"
    "github.com/yinshuwei/osm"
)

// User 用户Model
type User struct {
    ID         int64
    Email      string
    Nickname   string
    CreateTime time.Time
}

func main() {
    o, err := osm.New("mysql", "root:123456@/test?charset=utf8", []string{})
    if err != nil {
        fmt.Println(err.Error())
    }

    //添加
    user := User{
        Email:      "test@foxmail.com",
        Nickname:   "haha",
        CreateTime: time.Now(),
    }
    sql := "INSERT INTO user (email,nickname,create_time) VALUES (#{Email},#{Nickname},#{CreateTime});"
    fmt.Println(o.InsertBySQL(sql, user))

    //查询
    user = User{
        Email: "test@foxmail.com",
    }
    var results []User
    sql = "SELECT id,email,nickname,create_time FROM user WHERE email=#{Email};"
    _, err = o.SelectStructs(sql, user)(&results)
    if err != nil {
        fmt.Println(err.Error())
    }
    for _, u := range results {
        fmt.Println(u)
    }

    //删除
    fmt.Println(o.DeleteBySQL("DELETE FROM user WHERE email=#{Email}", user))

    err = o.Close()
    if err != nil {
        fmt.Println(err.Error())
    }
}
  • 执行template中的SQL(支持go template解析)示例

sql template文件test.xml

<?xml version="1.0" encoding="utf-8"?>
<osm>
    <insert id="insertUser">
    <![CDATA[
INSERT INTO user (email,nickname,create_time) VALUES (#{Email},#{Nickname},#{CreateTime});
    ]]>
    </insert>

    <select id="selectUser" result="structs">
    <![CDATA[
SELECT id,email,nickname,create_time FROM user 
WHERE 
{{if ne .Email ""}}email=#{Email} and{{end}}
{{if ne .Nickname ""}}nickname=#{Nickname} and{{end}}
1=1;
    ]]>
    </select>

    <delete id="deleteUser">
    <![CDATA[
DELETE FROM user WHERE email=#{Email}
    ]]>
    </delete>
</osm>

example.go

package main

import (
    "fmt"
    "time"

    _ "github.com/go-sql-driver/mysql"
    "github.com/yinshuwei/osm"
)

// User 用户model
type User struct {
    ID         int64
    Email      string
    Nickname   string
    CreateTime time.Time
}

func main() {
    o, err := osm.New("mysql", "root:root@/test?charset=utf8", []string{"test.xml"})
    if err != nil {
        fmt.Println(err.Error())
    }

    //添加
    user := User{
        Email:      "test@foxmail.com",
        Nickname:   "haha",
        CreateTime: time.Now(),
    }
    fmt.Println(o.Insert("insertUser", user))

    //动态查询
    user = User{
        Email: "test@foxmail.com",
    }
    var results []User
    o.Select("selectUser", user)(&results)
    for _, u := range results {
        fmt.Println(u)
    }

    //删除
    fmt.Println(o.Delete("deleteUser", user))

    err = o.Close()
    if err != nil {
        fmt.Println(err.Error())
    }
}

查询结果类型

  • value 查出的结果为单行,并存入不定长的变量上(...)

    xml

      <select id="selectResUserValue" result="value">
          SELECT id, email, head_image_url FROM res_user WHERE email=#{Email};
      </select>
    

    go

      user := ResUser{Email: "test@foxmail.com"}
      var id int64
      var email, headImageURL string
      o.Select("selectResUserValue", user)(&id, &email, &headImageURL)
    
      log.Println(id, email, headImageURL)
    
  • values 查出的结果为多行,并存入不定长的变量上(...,每个都为array,每个array长度都与结果集行数相同)

    xml

      <select id="selectResUserValues" result="values">
          SELECT id,email,head_image_url FROM res_user WHERE city=#{City} order by id;
      </select>
    

    go

      user := ResUser{City: "上海"}
      var ids []int64
      var emails, headImageUrls []string
      o.Select("selectResUserValues", user)(&ids, &emails, &headImageUrls)
    
      log.Println(ids, emails, headImageUrls)
    
  • struct 查出的结果为单行,并存入struct

    xml

      <select id="selectResUser" result="struct">
          SELECT id, email, head_image_url FROM res_user WHERE email=#{Email};
      </select>
    

    go

      user := ResUser{Email: "test@foxmail.com"}
      var result ResUser
      o.Select("selectResUser", user)(&result)
    
      log.Printf("%#v", result)
    
  • structs 查出的结果为多行,并存入struct array

    xml

      <select id="selectResUsers" result="structs">
          SELECT id,email,head_image_url FROM res_user WHERE city=#{City} order by id;
      </select>
    

    go

      user := ResUser{City: "上海"}
      var results []*ResUser // 或var results []ResUser
      o.Select("selectResUsers", user)(&results)
      log.Printf("%#v", results)
    
  • kvs 查出的结果为多行,每行有两个字段,前者为key,后者为value,存入map (双列)

    xml

      <select id="selectResUserKvs" result="kvs">
          SELECT id,email FROM res_user WHERE city=#{City} order by id;
      </select>
    

    go

      user := ResUser{City: "上海"}
      var idEmailMap map[int64]string
      o.Select("selectResUserKvs", user)(&idEmailMap)
      log.Println(idEmailMap)
    

struct与SQL列对应关系

  • 正常的转换过程

    用"_"分隔 (例:XXX_YYY -> XXX,YYY)

    每个部分全部转为首字大写其余字符小写 (例:XXX,YYY -> Xxx,Yyy)

    拼接(例:Xxx,Yyy -> XxxYyy)

  • 常见缩写单词,下面这些单词两种形式都可以,struct上可以任选其一。

    比如"UserId"和"UserID"可以正常对应到"user_id"列上。但是同一个struct中不可以既有"UserId"成员又有"UserID"成员,如果同时存在只会有一个成员会被赋值。

      Acl  或   ACL 
      Api  或   API 
      Ascii  或 ASCII 
      Cpu  或   CPU 
      Css  或   CSS 
      Dns  或   DNS 
      Eof  或   EOF 
      Guid  或  GUID 
      Html  或  HTML 
      Http  或  HTTP 
      Https  或 HTTPS 
      Id  或    ID 
      Ip  或    IP 
      Json  或  JSON 
      Lhs  或   LHS 
      Qps  或   QPS 
      Ram  或   RAM 
      Rhs  或   RHS 
      Rpc  或   RPC 
      Sla  或   SLA 
      Smtp  或  SMTP 
      Sql  或   SQL 
      Ssh  或   SSH 
      Tcp  或   TCP 
      Tls  或   TLS 
      Ttl  或   TTL 
      Udp  或   UDP 
      Ui  或    UI 
      Uid  或   UID 
      Uuid  或  UUID 
      Uri  或   URI 
      Url  或   URL 
      Utf8  或  UTF8 
      Vm  或    VM 
      Xml  或   XML 
      Xmpp  或  XMPP 
      Xsrf  或  XSRF 
      Xss  或   XSS 
    

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfLogger added in v1.0.9

func ConfLogger(_infoZapLogger, _errorZapLogger *zap.Logger, _showSQL bool)

Types

type Osm

type Osm struct {
	// contains filtered or unexported fields
}

Osm 对象,通过Struct、Map、Array、value等对象以及Sql Map来操作数据库。可以开启事务。

func New

func New(driverName, dataSource string, xmlPaths []string, params ...int) (*Osm, error)

New 创建一个新的Osm,这个过程会打开数据库连接。

driverName是数据库驱动名称如"mysql". dataSource是数据库连接信息如"root:root@/51jczj?charset=utf8". xmlPaths是sql xml的路径如[]string{"test.xml"}. params是数据连接的参数,可以是0个1个或2个数字,第一个表示MaxIdleConns,第二个表示MaxOpenConns.

如:

o, err := osm.New("mysql", "root:root@/51jczj?charset=utf8", []string{"test.xml"})

func (*Osm) Begin

func (o *Osm) Begin() (*Tx, error)

Begin 打开事务

如:

tx, err := o.Begin()

func (*Osm) Close

func (o *Osm) Close() error

Close 与数据库断开连接,释放连接资源

如:

err := o.Close()

func (*Osm) Delete

func (o *Osm) Delete(id string, params ...interface{}) (int64, error)

Delete 通过id在xml中找到删除sql并执行

xml

<osm>
...
  <delete id="deleteUser">DELETE FROM user where id = #{Id};</delete>
...
</osm>

代码

user := User{Id: 3}
count,err := o.Delete("deleteUser", user)

删除id为3的用户数据

func (*Osm) DeleteBySQL added in v1.0.4

func (o *Osm) DeleteBySQL(sql string, params ...interface{}) (int64, error)

DeleteBySQL 执行删除sql

代码

  count, err := o.DeleteBySQL(`DELETE FROM res_user WHERE id in #{Ids};`, []int64{1, 2})
  if err != nil {
	   log.Println(err)
  }
  log.Println("count:", count)

结果

count: 2

删除id为1和2的用户数据

func (*Osm) Insert

func (o *Osm) Insert(id string, params ...interface{}) (int64, int64, error)

Insert 通过id在xml中找到添加sql并执行

xml

<osm>
...
  <insert id="insertUser">INSERT INTO user(email) VALUES(#{Email});</insert>
...
</osm>

代码

user := User{Email: "test@foxmail.com"}
insertId,count,err := o.Insert("insertUser", user)

添加一个用户数据,email为"test@foxmail.com"

func (*Osm) InsertBySQL added in v1.0.4

func (o *Osm) InsertBySQL(sql string, params ...interface{}) (int64, int64, error)

InsertBySQL 执行添加sql

代码

  insertResUser := ResUser{
	  Email: "test@foxmail.com",
  }
  insertID, count, err := o.InsertBySQL("INSERT INTO res_user (email) VALUES(#{Email});", insertResUser)
  if err != nil {
	  log.Println(err)
  }
  log.Println("insertID:", insertID, "count:", count)

结果

insertID: 3 count: 1

添加一个用户数据,email为"test@foxmail.com"

func (*Osm) Select

func (o *Osm) Select(id string, params ...interface{}) func(containers ...interface{}) (int64, error)

通过id在xml中找到查询sql并执行

查询结果分为8种,分别是:

"value"   : 查出的结果为单行,并存入不定长的变量上(...),可以是指针,如var r1,r2 string、var r1,r2 *string
"values"  : 查出的结果为多行,并存入不定长的变量上(...,每个都为array),元素可以是指针,如var r1,r2 []string、var r1,r2 []*string都允许
"struct"  : 查出的结果为单行,并存入struct,可以是指针,如var r User、var r *User
"structs" : 查出的结果为多行,并存入struct array,元素可以是指针,如var r []User、var r []*User
"kvs"     : 查出的结果为多行,每行有两个字段,前者为key,后者为value,存入map (双列),Key、Value可以是指针,如var r map[string]time.Time、var r map[*string]time.Time、var r map[string]*time.Time
"strings" : 查出的结果为多行,并存入columns,和datas。columns为[]string,datas为[][]string

xml

<select id="searchArchives" result="struct">
 <![CDATA[
 SELECT id,email,create_time FROM user WHERE id=#{Id};
 ]]>
</select>

result上面8种的一种,查询结果会将列名转换为属性名,如"create_time"列,在结果中存放在CreateTime属性中

上面的结果为User{Id: "1", Email: "test@foxmail.com", CreateTime: "2014-06-01 12:32:40"}

func (*Osm) SelectKVS added in v1.0.4

func (o *Osm) SelectKVS(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectKVS 执行查询sql

查出的结果为多行,每行有两个字段,前者为key,后者为value,存入map (双列),Key、Value可以是指针,如var r map[string]time.Time、var r map[*string]time.Time、var r map[string]*time.Time

代码

  var idEmailMap = map[int64]string{}
  _, err = o.SelectKVS(`SELECT id,email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&idEmailMap)
  if err != nil {
	  log.Println(err)
  }
  log.Printf("idEmailMap: %v \n", idEmailMap)

结果

idEmailMap: map[1:test@foxmail.com 2:test@foxmail.com]

func (*Osm) SelectStrings added in v1.0.8

func (o *Osm) SelectStrings(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStrings 执行查询sql

查出的结果为多行,查出的结果为多行,并存入columns,和datas。columns为[]string,datas为[][]string

代码

  var columns []string
  var datas [][]string
  _, err = o.SelectStrings(`SELECT id,email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&columns, &datas)
  if err != nil {
	  log.Println(err)
  }
  log.Printf("columns: %v,datas: %v \n", columns, datas)

结果

columns: ["id", "email"]
datas: [["1",'test@foxmail.com'],["2","test@foxmail.com"]]

func (*Osm) SelectStruct added in v1.0.4

func (o *Osm) SelectStruct(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStruct 执行查询sql

查出的结果为单行,并存入struct,可以是指针,如var r User、var r *User

代码

  var users []ResUser
  _, err = o.SelectStruct(`SELECT id,email,create_time FROM res_user WHERE id=#{Id};`, 1)(&users)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("user: %#v \n", users)

结果

user: ResUser{ID:1, Email:"test@foxmail.com", Mobile:"", Nickname:""}

func (*Osm) SelectStructs added in v1.0.4

func (o *Osm) SelectStructs(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStructs 执行查询sql

查出的结果为多行,并存入struct array,元素可以是指针,如var r []User、var r []*User

代码

  var users []ResUser
  _, err = o.SelectStructs(`SELECT id,email,create_time FROM res_user WHERE id=#{Id};`, 1)(&users)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("users: %#v \n", users)

结果

users: []ResUser{ResUser{ID:1, Email:"test@foxmail.com", Mobile:"", Nickname:""}}

func (*Osm) SelectValue added in v1.0.4

func (o *Osm) SelectValue(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectValue 执行查询sql

查出的结果为单行,并存入不定长的变量上(...),可以是指针,如var r1,r2 string、var r1,r2 *string

代码

  var email string
  _, err = o.SelectValue(`SELECT email FROM res_user WHERE id=#{Id};`, 1)(&email)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("email: %s \n", email)

结果

email: test@foxmail.com

func (*Osm) SelectValues added in v1.0.4

func (o *Osm) SelectValues(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectValues 执行查询sql

查出的结果为多行,并存入不定长的变量上(...,每个都为array),元素可以是指针,如var r1,r2 []string、var r1,r2 []*string都允许

代码

  var emails []string
  _, err = o.SelectValues(`SELECT email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&emails)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("emails: %v \n", emails)

结果

emails: [test@foxmail.com test@foxmail.com]

func (*Osm) Update

func (o *Osm) Update(id string, params ...interface{}) (int64, error)

Update 通过id在xml中找到更新sql并执行

xml

<osm>
...
  <update id="updateUserEmail">UPDATE user SET email=#{Email} where id = #{Id};</update>
...
</osm>

代码

user := User{Id: 3, Email: "test@foxmail.com"}
count,err := o.Update("updateUserEmail", user)

将id为3的用户email更新为"test@foxmail.com"

func (*Osm) UpdateBySQL added in v1.0.4

func (o *Osm) UpdateBySQL(sql string, params ...interface{}) (int64, error)

UpdateBySQL 执行更新sql

代码

  count, err := o.UpdateBySQL(`UPDATE res_user SET email=#{Email} WHERE id=#{ID};`, "test2@foxmail.com", 3)
  if err != nil {
	  log.Println(err)
  }
  log.Println("count:", count)

结果

count: 1

将id为1的用户email更新为"test2@foxmail.com"

func (*Osm) UpdateMulti

func (o *Osm) UpdateMulti(id string, params ...interface{}) error

UpdateMulti 批量通过id在xml中找到更新sql并执行

xml

<osm>
...
  <update id="updateUserEmail">
     UPDATE user SET email=#{Email} where id = #{Id};
     UPDATE user SET email=#{Email} where id = #{Id2};
  </update>
...
</osm>

代码

user := User{Id: 3, Id2: 4, Email: "test@foxmail.com"}
err := o.UpdateMulti("updateUserEmail", user)

将id为3和4的用户email更新为"test@foxmail.com"

func (*Osm) UpdateMultiBySQL added in v1.0.6

func (o *Osm) UpdateMultiBySQL(sql string, params ...interface{}) error

UpdateMultiBySQL 批量执行更新sql

代码

user := User{Id: 3, Id2: 4, Email: "test@foxmail.com"}
err := o.UpdateMultiBySQL(`
     UPDATE user SET email='#{Email}' where id = #{Id};
     UPDATE user SET email='#{Email}' where id = #{Id2};`, user)

将id为3和4的用户email更新为"test@foxmail.com"

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

Tx 与Osm对象一样,不过是在事务中进行操作

func (*Tx) Commit

func (o *Tx) Commit() error

Commit 提交事务

如:

err := tx.Commit()

func (*Tx) Delete

func (o *Tx) Delete(id string, params ...interface{}) (int64, error)

Delete 通过id在xml中找到删除sql并执行

xml

<osm>
...
  <delete id="deleteUser">DELETE FROM user where id = #{Id};</delete>
...
</osm>

代码

user := User{Id: 3}
count,err := o.Delete("deleteUser", user)

删除id为3的用户数据

func (*Tx) DeleteBySQL added in v1.0.4

func (o *Tx) DeleteBySQL(sql string, params ...interface{}) (int64, error)

DeleteBySQL 执行删除sql

代码

  count, err := o.DeleteBySQL(`DELETE FROM res_user WHERE id in #{Ids};`, []int64{1, 2})
  if err != nil {
	   log.Println(err)
  }
  log.Println("count:", count)

结果

count: 2

删除id为1和2的用户数据

func (*Tx) Insert

func (o *Tx) Insert(id string, params ...interface{}) (int64, int64, error)

Insert 通过id在xml中找到添加sql并执行

xml

<osm>
...
  <insert id="insertUser">INSERT INTO user(email) VALUES(#{Email});</insert>
...
</osm>

代码

user := User{Email: "test@foxmail.com"}
insertId,count,err := o.Insert("insertUser", user)

添加一个用户数据,email为"test@foxmail.com"

func (*Tx) InsertBySQL added in v1.0.4

func (o *Tx) InsertBySQL(sql string, params ...interface{}) (int64, int64, error)

InsertBySQL 执行添加sql

代码

  insertResUser := ResUser{
	  Email: "test@foxmail.com",
  }
  insertID, count, err := o.InsertBySQL("INSERT INTO res_user (email) VALUES(#{Email});", insertResUser)
  if err != nil {
	  log.Println(err)
  }
  log.Println("insertID:", insertID, "count:", count)

结果

insertID: 3 count: 1

添加一个用户数据,email为"test@foxmail.com"

func (*Tx) Rollback

func (o *Tx) Rollback() error

Rollback 事务回滚

如:

err := tx.Rollback()

func (*Tx) Select

func (o *Tx) Select(id string, params ...interface{}) func(containers ...interface{}) (int64, error)

通过id在xml中找到查询sql并执行

查询结果分为8种,分别是:

"value"   : 查出的结果为单行,并存入不定长的变量上(...),可以是指针,如var r1,r2 string、var r1,r2 *string
"values"  : 查出的结果为多行,并存入不定长的变量上(...,每个都为array),元素可以是指针,如var r1,r2 []string、var r1,r2 []*string都允许
"struct"  : 查出的结果为单行,并存入struct,可以是指针,如var r User、var r *User
"structs" : 查出的结果为多行,并存入struct array,元素可以是指针,如var r []User、var r []*User
"kvs"     : 查出的结果为多行,每行有两个字段,前者为key,后者为value,存入map (双列),Key、Value可以是指针,如var r map[string]time.Time、var r map[*string]time.Time、var r map[string]*time.Time
"strings" : 查出的结果为多行,并存入columns,和datas。columns为[]string,datas为[][]string

xml

<select id="searchArchives" result="struct">
 <![CDATA[
 SELECT id,email,create_time FROM user WHERE id=#{Id};
 ]]>
</select>

result上面8种的一种,查询结果会将列名转换为属性名,如"create_time"列,在结果中存放在CreateTime属性中

上面的结果为User{Id: "1", Email: "test@foxmail.com", CreateTime: "2014-06-01 12:32:40"}

func (*Tx) SelectKVS added in v1.0.4

func (o *Tx) SelectKVS(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectKVS 执行查询sql

查出的结果为多行,每行有两个字段,前者为key,后者为value,存入map (双列),Key、Value可以是指针,如var r map[string]time.Time、var r map[*string]time.Time、var r map[string]*time.Time

代码

  var idEmailMap = map[int64]string{}
  _, err = o.SelectKVS(`SELECT id,email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&idEmailMap)
  if err != nil {
	  log.Println(err)
  }
  log.Printf("idEmailMap: %v \n", idEmailMap)

结果

idEmailMap: map[1:test@foxmail.com 2:test@foxmail.com]

func (*Tx) SelectStrings added in v1.0.8

func (o *Tx) SelectStrings(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStrings 执行查询sql

查出的结果为多行,查出的结果为多行,并存入columns,和datas。columns为[]string,datas为[][]string

代码

  var columns []string
  var datas [][]string
  _, err = o.SelectStrings(`SELECT id,email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&columns, &datas)
  if err != nil {
	  log.Println(err)
  }
  log.Printf("columns: %v,datas: %v \n", columns, datas)

结果

columns: ["id", "email"]
datas: [["1",'test@foxmail.com'],["2","test@foxmail.com"]]

func (*Tx) SelectStruct added in v1.0.4

func (o *Tx) SelectStruct(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStruct 执行查询sql

查出的结果为单行,并存入struct,可以是指针,如var r User、var r *User

代码

  var users []ResUser
  _, err = o.SelectStruct(`SELECT id,email,create_time FROM res_user WHERE id=#{Id};`, 1)(&users)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("user: %#v \n", users)

结果

user: ResUser{ID:1, Email:"test@foxmail.com", Mobile:"", Nickname:""}

func (*Tx) SelectStructs added in v1.0.4

func (o *Tx) SelectStructs(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectStructs 执行查询sql

查出的结果为多行,并存入struct array,元素可以是指针,如var r []User、var r []*User

代码

  var users []ResUser
  _, err = o.SelectStructs(`SELECT id,email,create_time FROM res_user WHERE id=#{Id};`, 1)(&users)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("users: %#v \n", users)

结果

users: []ResUser{ResUser{ID:1, Email:"test@foxmail.com", Mobile:"", Nickname:""}}

func (*Tx) SelectValue added in v1.0.4

func (o *Tx) SelectValue(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectValue 执行查询sql

查出的结果为单行,并存入不定长的变量上(...),可以是指针,如var r1,r2 string、var r1,r2 *string

代码

  var email string
  _, err = o.SelectValue(`SELECT email FROM res_user WHERE id=#{Id};`, 1)(&email)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("email: %s \n", email)

结果

email: test@foxmail.com

func (*Tx) SelectValues added in v1.0.4

func (o *Tx) SelectValues(sql string, params ...interface{}) func(containers ...interface{}) (int64, error)

SelectValues 执行查询sql

查出的结果为多行,并存入不定长的变量上(...,每个都为array),元素可以是指针,如var r1,r2 []string、var r1,r2 []*string都允许

代码

  var emails []string
  _, err = o.SelectValues(`SELECT email FROM res_user WHERE id in #{Ids};`, []int64{1, 2})(&emails)
  if err != nil {
	   log.Println(err)
  }
  log.Printf("emails: %v \n", emails)

结果

emails: [test@foxmail.com test@foxmail.com]

func (*Tx) Update

func (o *Tx) Update(id string, params ...interface{}) (int64, error)

Update 通过id在xml中找到更新sql并执行

xml

<osm>
...
  <update id="updateUserEmail">UPDATE user SET email=#{Email} where id = #{Id};</update>
...
</osm>

代码

user := User{Id: 3, Email: "test@foxmail.com"}
count,err := o.Update("updateUserEmail", user)

将id为3的用户email更新为"test@foxmail.com"

func (*Tx) UpdateBySQL added in v1.0.4

func (o *Tx) UpdateBySQL(sql string, params ...interface{}) (int64, error)

UpdateBySQL 执行更新sql

代码

  count, err := o.UpdateBySQL(`UPDATE res_user SET email=#{Email} WHERE id=#{ID};`, "test2@foxmail.com", 3)
  if err != nil {
	  log.Println(err)
  }
  log.Println("count:", count)

结果

count: 1

将id为1的用户email更新为"test2@foxmail.com"

func (*Tx) UpdateMulti

func (o *Tx) UpdateMulti(id string, params ...interface{}) error

UpdateMulti 批量通过id在xml中找到更新sql并执行

xml

<osm>
...
  <update id="updateUserEmail">
     UPDATE user SET email=#{Email} where id = #{Id};
     UPDATE user SET email=#{Email} where id = #{Id2};
  </update>
...
</osm>

代码

user := User{Id: 3, Id2: 4, Email: "test@foxmail.com"}
err := o.UpdateMulti("updateUserEmail", user)

将id为3和4的用户email更新为"test@foxmail.com"

func (*Tx) UpdateMultiBySQL added in v1.0.6

func (o *Tx) UpdateMultiBySQL(sql string, params ...interface{}) error

UpdateMultiBySQL 批量执行更新sql

代码

user := User{Id: 3, Id2: 4, Email: "test@foxmail.com"}
err := o.UpdateMultiBySQL(`
     UPDATE user SET email='#{Email}' where id = #{Id};
     UPDATE user SET email='#{Email}' where id = #{Id2};`, user)

将id为3和4的用户email更新为"test@foxmail.com"

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL