I'm trying to read data from a MySQL database from my Go app.
var queryStr string = "SELECT * FROM Customers"
rows, err := db.Query(queryStr)
defer rows.Close()
for rows.Next() {
// do stuffs
}
The query it's ok and it works; now I'd like to easily map each record of the MySQL query to a Customer object that I've previuosly defined as showed below:
type Customer struct {
id IntegerType `json:"id"`
name string `json:"name"`
surname string `json:"surname"`
}
How can I do that?
Second question: once I get an array of Customer object how can I easily put it into a new JSON object under a specific key called "data"?
thanks for your support :)
Export fields so they can be used on JSON:
type Customer struct {
ID int `json:"id"`
Name string `json:"name"`
Surname string `json:"surname"`
}
Declare a value to be marshaled to JSON:
var v struct {
Data []Customer `json:"data"`
}
Query for the specific fields:
var queryStr string = "SELECT id, name, surname FROM Customers"
rows, err := db.Query(queryStr)
Loop through rows adding to value.
defer rows.Close()
for rows.Next() {
// Scan one customer record
var c Customer
if err := rows.Scan(&c.ID, &c.Name, &c.Surnmae); err != nil {
// handle error
}
v.Data = append(v.Data, c)
}
if rows.Err() != nil {
// handle error
}
Marshal the value to JSON
p, err := json.Marshal(v)
if err != nil {
// handle error
}
The value p
is a []byte containing the JSON.