Go语言的ORM库xorm实战篇

          Go语言的ORM库xorm实战篇

                                 作者:尹正杰

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

   xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。

 

一.环境准备

1>.准备测试数据

[root@yinzhengjie.com ~]# yum -y install mariadb-server
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                                                                                 | 6.6 kB  00:00:00     
 * base: mirrors.bfsu.edu.cn
 * epel: hkg.mirror.rackspace.com
 * extras: mirrors.bfsu.edu.cn
 * updates: mirrors.bfsu.edu.cn
base                                                                                                                                                 | 3.6 kB  00:00:00     
epel                                                                                                                                                 | 4.7 kB  00:00:00     
extras                                                                                                                                               | 2.9 kB  00:00:00     
updates                                                                                                                                              | 2.9 kB  00:00:00     
(1/3): updates/7/x86_64/primary_db                                                                                                                   | 1.3 MB  00:00:00     
(2/3): epel/x86_64/updateinfo                                                                                                                        | 1.0 MB  00:00:01     
epel/x86_64/primary_db         FAILED                                          
http://hk.mirrors.thegigabit.com/epel/7/x86_64/repodata/c0bb886c57e1b6e3dc9bcc5569e4b0231ef9d641a0ee033573d3e02d9a233952-primary.sqlite.bz2: [Errno 14] HTTP Error 404 - Not
 FoundTrying other mirror.
To address this issue please refer to the below wiki article 

https://wiki.centos.org/yum-errors

If above article doesn't help to resolve this issue please use https://bugs.centos.org/.

(3/3): epel/x86_64/primary_db                                                                                                                        | 6.8 MB  00:00:01     
Resolving Dependencies
--> Running transaction check
---> Package mariadb-server.x86_64 1:5.5.65-1.el7 will be installed
--> Processing Dependency: mariadb-libs(x86-64) = 1:5.5.65-1.el7 for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Processing Dependency: mariadb(x86-64) = 1:5.5.65-1.el7 for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Processing Dependency: perl-DBI for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Processing Dependency: perl-DBD-MySQL for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Processing Dependency: perl(Data::Dumper) for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Processing Dependency: perl(DBI) for package: 1:mariadb-server-5.5.65-1.el7.x86_64
--> Running transaction check
---> Package mariadb.x86_64 1:5.5.65-1.el7 will be installed
---> Package mariadb-libs.x86_64 1:5.5.60-1.el7_5 will be updated
---> Package mariadb-libs.x86_64 1:5.5.65-1.el7 will be an update
---> Package perl-DBD-MySQL.x86_64 0:4.023-6.el7 will be installed
---> Package perl-DBI.x86_64 0:1.627-4.el7 will be installed
--> Processing Dependency: perl(RPC::PlServer) >= 0.2001 for package: perl-DBI-1.627-4.el7.x86_64
--> Processing Dependency: perl(RPC::PlClient) >= 0.2000 for package: perl-DBI-1.627-4.el7.x86_64
---> Package perl-Data-Dumper.x86_64 0:2.145-3.el7 will be installed
--> Running transaction check
---> Package perl-PlRPC.noarch 0:0.2020-14.el7 will be installed
--> Processing Dependency: perl(Net::Daemon) >= 0.13 for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Net::Daemon::Test) for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Net::Daemon::Log) for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Compress::Zlib) for package: perl-PlRPC-0.2020-14.el7.noarch
--> Running transaction check
---> Package perl-IO-Compress.noarch 0:2.061-2.el7 will be installed
--> Processing Dependency: perl(Compress::Raw::Zlib) >= 2.061 for package: perl-IO-Compress-2.061-2.el7.noarch
--> Processing Dependency: perl(Compress::Raw::Bzip2) >= 2.061 for package: perl-IO-Compress-2.061-2.el7.noarch
---> Package perl-Net-Daemon.noarch 0:0.48-5.el7 will be installed
--> Running transaction check
---> Package perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7 will be installed
---> Package perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

============================================================================================================================================================================
 Package                                             Arch                               Version                                      Repository                        Size
============================================================================================================================================================================
Installing:
 mariadb-server                                      x86_64                             1:5.5.65-1.el7                               base                              11 M
Installing for dependencies:
 mariadb                                             x86_64                             1:5.5.65-1.el7                               base                             8.7 M
 perl-Compress-Raw-Bzip2                             x86_64                             2.061-3.el7                                  base                              32 k
 perl-Compress-Raw-Zlib                              x86_64                             1:2.061-4.el7                                base                              57 k
 perl-DBD-MySQL                                      x86_64                             4.023-6.el7                                  base                             140 k
 perl-DBI                                            x86_64                             1.627-4.el7                                  base                             802 k
 perl-Data-Dumper                                    x86_64                             2.145-3.el7                                  base                              47 k
 perl-IO-Compress                                    noarch                             2.061-2.el7                                  base                             260 k
 perl-Net-Daemon                                     noarch                             0.48-5.el7                                   base                              51 k
 perl-PlRPC                                          noarch                             0.2020-14.el7                                base                              36 k
Updating for dependencies:
 mariadb-libs                                        x86_64                             1:5.5.65-1.el7                               base                             759 k

Transaction Summary
============================================================================================================================================================================
Install  1 Package  (+9 Dependent packages)
Upgrade             ( 1 Dependent package)

Total download size: 22 M
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
(1/11): perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64.rpm                                                                                               |  32 kB  00:00:00     
(2/11): mariadb-libs-5.5.65-1.el7.x86_64.rpm                                                                                                         | 759 kB  00:00:00     
(3/11): perl-Compress-Raw-Zlib-2.061-4.el7.x86_64.rpm                                                                                                |  57 kB  00:00:00     
(4/11): perl-DBD-MySQL-4.023-6.el7.x86_64.rpm                                                                                                        | 140 kB  00:00:00     
(5/11): perl-DBI-1.627-4.el7.x86_64.rpm                                                                                                              | 802 kB  00:00:00     
(6/11): perl-Data-Dumper-2.145-3.el7.x86_64.rpm                                                                                                      |  47 kB  00:00:00     
(7/11): perl-Net-Daemon-0.48-5.el7.noarch.rpm                                                                                                        |  51 kB  00:00:00     
(8/11): perl-IO-Compress-2.061-2.el7.noarch.rpm                                                                                                      | 260 kB  00:00:00     
(9/11): mariadb-5.5.65-1.el7.x86_64.rpm                                                                                                              | 8.7 MB  00:00:02     
(10/11): mariadb-server-5.5.65-1.el7.x86_64.rpm                                                                                                      |  11 MB  00:00:02     
(11/11): perl-PlRPC-0.2020-14.el7.noarch.rpm                                                                                                         |  36 kB  00:00:00     
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                       9.5 MB/s |  22 MB  00:00:02     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Updating   : 1:mariadb-libs-5.5.65-1.el7.x86_64                                                                                                                      1/12 
  Installing : perl-Data-Dumper-2.145-3.el7.x86_64                                                                                                                     2/12 
  Installing : 1:mariadb-5.5.65-1.el7.x86_64                                                                                                                           3/12 
  Installing : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64                                                                                                             4/12 
  Installing : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64                                                                                                              5/12 
  Installing : perl-IO-Compress-2.061-2.el7.noarch                                                                                                                     6/12 
  Installing : perl-Net-Daemon-0.48-5.el7.noarch                                                                                                                       7/12 
  Installing : perl-PlRPC-0.2020-14.el7.noarch                                                                                                                         8/12 
  Installing : perl-DBI-1.627-4.el7.x86_64                                                                                                                             9/12 
  Installing : perl-DBD-MySQL-4.023-6.el7.x86_64                                                                                                                      10/12 
  Installing : 1:mariadb-server-5.5.65-1.el7.x86_64                                                                                                                   11/12 
  Cleanup    : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                                                                                   12/12 
  Verifying  : 1:mariadb-server-5.5.65-1.el7.x86_64                                                                                                                    1/12 
  Verifying  : perl-Net-Daemon-0.48-5.el7.noarch                                                                                                                       2/12 
  Verifying  : perl-Data-Dumper-2.145-3.el7.x86_64                                                                                                                     3/12 
  Verifying  : perl-DBD-MySQL-4.023-6.el7.x86_64                                                                                                                       4/12 
  Verifying  : 1:mariadb-libs-5.5.65-1.el7.x86_64                                                                                                                      5/12 
  Verifying  : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64                                                                                                              6/12 
  Verifying  : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64                                                                                                             7/12 
  Verifying  : perl-DBI-1.627-4.el7.x86_64                                                                                                                             8/12 
  Verifying  : perl-IO-Compress-2.061-2.el7.noarch                                                                                                                     9/12 
  Verifying  : perl-PlRPC-0.2020-14.el7.noarch                                                                                                                        10/12 
  Verifying  : 1:mariadb-5.5.65-1.el7.x86_64                                                                                                                          11/12 
  Verifying  : 1:mariadb-libs-5.5.60-1.el7_5.x86_64                                                                                                                   12/12 

Installed:
  mariadb-server.x86_64 1:5.5.65-1.el7                                                                                                                                      

Dependency Installed:
  mariadb.x86_64 1:5.5.65-1.el7        perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7    perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7    perl-DBD-MySQL.x86_64 0:4.023-6.el7   
  perl-DBI.x86_64 0:1.627-4.el7        perl-Data-Dumper.x86_64 0:2.145-3.el7           perl-IO-Compress.noarch 0:2.061-2.el7          perl-Net-Daemon.noarch 0:0.48-5.el7   
  perl-PlRPC.noarch 0:0.2020-14.el7   

Dependency Updated:
  mariadb-libs.x86_64 1:5.5.65-1.el7                                                                                                                                        

Complete!
[root@yinzhengjie.com ~]# 
[root@yinzhengjie.com ~]# yum -y install mariadb-server
[root@yinzhengjie.com ~]# systemctl start mariadb
[root@yinzhengjie.com ~]# 
[root@yinzhengjie.com ~]# systemctl enable mariadb
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@yinzhengjie.com ~]# 
[root@yinzhengjie.com ~]# systemctl start mariadb
[root@yinzhengjie.com ~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.65-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 
MariaDB [(none)]> create database golang CHARACTER SET utf8mb4;
Query OK, 1 row affected (0.03 sec)

MariaDB [(none)]>
MariaDB [(none)]> CREATE USER jason@'%' IDENTIFIED BY 'yinzhengjie';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> 
MariaDB [(none)]> GRANT ALL ON golang.* TO jason@'%';
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> 
MariaDB [(none)]> quit
Bye
[root@yinzhengjie.com ~]# 

2>.安装xorm驱动

  GitHub地址:
    https://github.com/go-xorm/xorm

  安装xorm驱动:
    go get github.com/go-xorm/xorm

3>.安装mysql驱动

  安装Go语言的MySQL驱动:
    go get  github.com/go-sql-driver/mysql

 

 

二.查询操作 

1>.查询所有数据

package main

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

//结构体字段对应数据库中的表字段
type User struct {
    Id      int64
    Name    string `xorm:"name"`
    Age     int    `xorm:"age"`
    Phone   string `xorm:"phone"`
    Address string `xorm:"address"`
}

func main() {
    /**
    配置连接数据库信息格式如下所示:
        用户名:密码@tcp(数据库服务器地址:端口)/数据库名称?charset=字符集
    */
    cmd := fmt.Sprintf("jason:yinzhengjie@tcp(172.200.1.254:3306)/golang?charset=utf8mb4")

    //使用上面的配置信息连接数据库,但要指定数据库的类型(我这里写MySQL)
    db_conn, err := xorm.NewEngine("mysql", cmd)
    if err != nil {
        log.Fatal(err)
    }

    //释放资源
    defer db_conn.Close()

    users := make([]User, 0) //等效于"var users []User"

    //获取所有资源
    err = db_conn.Find(&users)
    if err != nil {
        log.Println(err)
    } else {
        for _, user := range users {
            log.Println(user.Id, user.Name, user.Age, user.Address)
        }
    }
}
案例代码

2>.过滤查询数据

package main

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

//结构体字段对应数据库中的表字段
type User struct {
    Id      int64
    Name    string `xorm:"name"`
    Age     int    `xorm:"age"`
    Phone   string `xorm:"phone"`
    Address string `xorm:"address"`
}

func main() {
    /**
    配置连接数据库信息格式如下所示:
        用户名:密码@tcp(数据库服务器地址:端口)/数据库名称?charset=字符集
    */
    cmd := fmt.Sprintf("jason:yinzhengjie@tcp(172.200.1.254:3306)/golang?charset=utf8mb4")

    //使用上面的配置信息连接数据库,但要指定数据库的类型(我这里写MySQL)
    db_conn, err := xorm.NewEngine("mysql", cmd)
    if err != nil {
        log.Fatal(err)
    }

    //释放资源
    defer db_conn.Close()

    var users []User //等效于"users := make([]User, 0)"

    //过滤数据(年龄在19-25岁之间)
    err = db_conn.Where("age > ? and age < ?", 19, 25).Find(&users)
    if err != nil {
        log.Println(err)
    } else {
        for _, user := range users {
            log.Println(user.Id, user.Name, user.Age, user.Address)
        }
    }
}
案例代码

 

三.插入操作

package main

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

//结构体字段对应数据库中的表字段
type User struct {
    Id      int64
    Name    string `xorm:"name"`
    Age     int    `xorm:"age"`
    Phone   string `xorm:"phone"`
    Address string `xorm:"address"`
}

func main() {
    /**
    配置连接数据库信息格式如下所示:
        用户名:密码@tcp(数据库服务器地址:端口)/数据库名称?charset=字符集
    */
    cmd := fmt.Sprintf("jason:yinzhengjie@tcp(172.200.1.254:3306)/golang?charset=utf8mb4")

    //使用上面的配置信息连接数据库,但要指定数据库的类型(我这里写MySQL)
    db_conn, err := xorm.NewEngine("mysql", cmd)
    if err != nil {
        log.Fatal(err)
    }

    //释放资源
    defer db_conn.Close()

    //定义待插入用户的数据
    new_user := User{
        Id:      3,
        Name:    "诡术妖姬",
        Age:     25,
        Phone:   "1000001",
        Address: "艾欧尼亚",
    }

    n, err := db_conn.Insert(new_user)
    fmt.Printf("成功插入了[%d]条数据!\n", n)
}
案例代码

 

四.删除操作

package main

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

//结构体字段对应数据库中的表字段
type User struct {
    Id      int64
    Name    string `xorm:"name"`
    Age     int    `xorm:"age"`
    Phone   string `xorm:"phone"`
    Address string `xorm:"address"`
}

func main() {
    /**
    配置连接数据库信息格式如下所示:
        用户名:密码@tcp(数据库服务器地址:端口)/数据库名称?charset=字符集
    */
    cmd := fmt.Sprintf("jason:yinzhengjie@tcp(172.200.1.254:3306)/golang?charset=utf8mb4")

    //使用上面的配置信息连接数据库,但要指定数据库的类型(我这里写MySQL)
    db_conn, err := xorm.NewEngine("mysql", cmd)
    if err != nil {
        log.Fatal(err)
    }

    //释放资源
    defer db_conn.Close()

    user := User{}

    //定义删除name字段为"诡术妖姬"的数据
    n, err := db_conn.Where("name = ?", "诡术妖姬").Delete(user)
    if err != nil {
        log.Println(err)
    }
    fmt.Printf("成功删除了[%d]条数据!\n", n)
}
案例代码

 

五.更新操作

package main

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

//结构体字段对应数据库中的表字段
type User struct {
    Id      int64
    Name    string `xorm:"name"`
    Age     int    `xorm:"age"`
    Phone   string `xorm:"phone"`
    Address string `xorm:"address"`
}

func main() {
    /**
    配置连接数据库信息格式如下所示:
        用户名:密码@tcp(数据库服务器地址:端口)/数据库名称?charset=字符集
    */
    cmd := fmt.Sprintf("jason:yinzhengjie@tcp(172.200.1.254:3306)/golang?charset=utf8mb4")

    //使用上面的配置信息连接数据库,但要指定数据库的类型(我这里写MySQL)
    db_conn, err := xorm.NewEngine("mysql", cmd)
    if err != nil {
        log.Fatal(err)
    }

    //释放资源
    defer db_conn.Close()

    //定义待更新的字段内容
    user := User{Age: 27}

    //定义删除name字段为"诡术妖姬"的数据
    n, err := db_conn.Where("id = ?", 1).Update(user)
    if err != nil {
        log.Println(err)
    }
    fmt.Printf("成功更新了[%d]条数据!\n", n)
}
案例代码

 

posted @ 2020-05-15 22:20  JasonYin2020  阅读(2589)  评论(0编辑  收藏  举报