How do I send an object to MySQL? Thanks
评论:
dallbee:
fnetma: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)
adelowo: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
}
Damn, I never knew you could do this
