Send an object to MySQL?

agolangf · 2017-08-10 01:18:46 · 696 次点击    
这是一个分享于 2017-08-10 01:18:46 的资源,其中的信息可能已经有所发展或是发生改变。

How do I send an object to MySQL? Thanks


评论:

dallbee:

You can't directly insert an object like you might hope, but there's some third party packages that can help with this: https://jmoiron.github.io/sqlx/

type Book struct {
    id int
    name string
}
book := Book{0, "Example"}
db = sqlx.MustConnect("mysql", dsn)
db.NamedExec(`INSERT INTO books (id, name) VALUES (:id, :name)`, &book)
fnetma:

How does this look? The struct is type Data.

dat, err = models.ParseDashboardPacket(buf[:47])
        if err == nil {
            models.PrintDashboard(dat)

tx := db.MustBegin()
            tx.NamedExec("INSERT INTO Data (status, acceleration, 
                position, velocity, battery_voltage, battery_current, 
                battery_temperature, pod_temperature, stripe_count, pod_pressure,
                 switch_states, pr_p1, pr_p2, br_p1, br_p2, br_p3)
              VALUES (:id, :team_id, :status, :acceleration, :position,:velocity, 
                    :battery_voltage, :battery_current, :battery_temperature, 
                    :pod_temperature, :stripe_count, :pod_pressure, :switch_states, 
                    :pr_p1,:pr_p2, :br_p1, :br_p2,:br_p3,:br_p4)", &dat)
                tx.Commit()


func ParseDashboardPacket(buf []byte) (Data, error) {
ret := Data{}
if len(buf) != 47 {
    return ret, errors.New("Dashboard Packet: incorrect slice length")
}
ret, err := ParsePacket(buf[:34])
if err != nil {
    return ret, err
}
// TODO: parse rest of packet
return ret, nil

}

adelowo:

Damn, I never knew you could do this


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

696 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传