Golang与mysql的json数据互通

程序

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()      //根据列分类 存储进一个[]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() //在go中所对应的类型
	type2 := columnTypes[1].ScanType()
	fmt.Println(type1, type2)
	var book Book
	var ( //使用sql.RawBytes来接收数据库中查询出来的json数据
		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>

你可能感兴趣的:(Go基础)