美文网首页
golang连结Mysql

golang连结Mysql

作者: 次序 | 来源:发表于2020-07-19 11:01 被阅读0次
    package main
    
    import (
        "fmt"
        "io/ioutil"
    
        "github.com/golang/snappy"
    
        "github.com/jinzhu/gorm"
        _ "github.com/jinzhu/gorm/dialects/mysql"
    )
    
    type User struct {
        ID   int
        Text []byte `gorm:"type:blob"`
    }
    
    var mysql *gorm.DB
    
    func init() {
        var err error
        mysql, err = gorm.Open("mysql", "root:nikki@(127.0.0.1:3306)/test?timeout=5s&parseTime=true&loc=Local&charset=utf8")
        if err != nil {
            panic(err)
        }
    
        mysql.AutoMigrate(&User{})
    }
    
    func main() {
        text, err := ioutil.ReadFile("text")
        if err != nil {
            panic(err)
        }
        fmt.Println("Text Size:", len(text))
    
        {
            u := &User{ID: 1}
            u.Text = snappy.Encode(nil, text)
            if err := mysql.Create(u).Error; err != nil {
                panic(err)
            }
        }
        {
            u := &User{ID: 1}
            if err := mysql.First(u).Error; err != nil {
                panic(err)
            }
            fmt.Println("Text snappy Size:", len(u.Text))
            textRead, err := snappy.Decode(nil, u.Text)
            if err != nil {
                panic(err)
            }
            if string(text) != string(textRead) {
                panic("unexpected")
            }
            fmt.Println("Text snappy Decode Size:", len(textRead))
            fmt.Println("Text snappy:", float32(len(textRead))/float32(len(u.Text)))
            if err := mysql.Delete(u).Error; err != nil {
                panic(err)
            }
        }
    }
    
    

    相关文章

      网友评论

          本文标题:golang连结Mysql

          本文链接:https://www.haomeiwen.com/subject/ckelkktx.html