程序
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type Book struct {
id int
category Category
tags []int
}
type Category struct {
Id int
Name string
}
func main() {
db, _ := sql.Open("mysql", "root:123@/xty")
rows, _ := db.Query("select category,tags from book where id=?", 2)
columnTypes, _ := rows.ColumnTypes()
str1 := columnTypes[0].DatabaseTypeName()
name1 := columnTypes[0].Name()
str2 := columnTypes[1].DatabaseTypeName()
name2 := columnTypes[1].Name()
fmt.Println(str1, str2)
fmt.Println(name1, name2)
type1 := columnTypes[0].ScanType()
type2 := columnTypes[1].ScanType()
fmt.Println(type1, type2)
var book Book
var (
category sql.RawBytes
tags sql.RawBytes
)
for rows.Next() {
rows.Scan(&category, &tags)
}
json.Unmarshal(category, &book.category)
json.Unmarshal(tags, &book.tags)
fmt.Println(book)
c := Category{Id: 9, Name: "sword coming"}
t := []int{1, 2, 3, 4, 5, 6, 7}
c2j, err := json.Marshal(c)
t2j, err := json.Marshal(t)
res, err := db.Exec("insert into book(id,category,tags) values(?,?,?)", 4, c2j, t2j)
if err != nil {
panic(err)
}
fmt.Println(res.LastInsertId())
}
结果
JSON JSON
category tags
sql.RawBytes sql.RawBytes
{0 {2 walk in the daynight} [4 5 6]}
4 <nil>