Send an object to MySQL?

agolangf · · 514 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>How do I send an object to MySQL? Thanks</p> <hr/>**评论:**<br/><br/>dallbee: <pre><p>You can&#39;t directly insert an object like you might hope, but there&#39;s some third party packages that can help with this: <a href="https://jmoiron.github.io/sqlx/" rel="nofollow">https://jmoiron.github.io/sqlx/</a></p> <pre><code>type Book struct { id int name string } book := Book{0, &#34;Example&#34;} db = sqlx.MustConnect(&#34;mysql&#34;, dsn) db.NamedExec(`INSERT INTO books (id, name) VALUES (:id, :name)`, &amp;book) </code></pre></pre>fnetma: <pre><p>How does this look? The struct is type Data.</p> <pre><code>dat, err = models.ParseDashboardPacket(buf[:47]) if err == nil { models.PrintDashboard(dat) tx := db.MustBegin() tx.NamedExec(&#34;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)&#34;, &amp;dat) tx.Commit() func ParseDashboardPacket(buf []byte) (Data, error) { ret := Data{} if len(buf) != 47 { return ret, errors.New(&#34;Dashboard Packet: incorrect slice length&#34;) } ret, err := ParsePacket(buf[:34]) if err != nil { return ret, err } // TODO: parse rest of packet return ret, nil </code></pre> <p>}</p></pre>adelowo: <pre><p>Damn, I never knew you could do this</p></pre>

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

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