Golang与mysql的json数据互通
2019-04-12 10:08
435 查看
程序
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>
相关文章推荐
- mysql使用like模糊搜索json的数据
- php查询mysql,返回json格式数据
- json数据持久到MySQL
- 利用Golang解析json数据的方法示例
- mysql中json数据的拼接方式
- Flex(ActionScript3)+JSON+PHP+MySQL的Web框架的数据传递
- golang mysql 诊断之旅(2000万开房数据被曝光引发的血案)
- sqoop把mysql数据导入hive中,报错:java.lang.NullPointerException at org.json.JSONObject.
- 使用json unmarshal数据到interface{}, 数字变成float64,,golang
- golang接收post接收xml或者json数据
- java获取mysql数据,resultSetToJson,结果集转换成json数组
- MySQL 5.7 Use The JSON Data Type(MySQL 使用 JSON 数据类型)
- 对MySQL中JSON数据类型的操作和分析
- php解决插入数据时mysql对json_encode值的反斜杠进行转义
- Golang JSON Unmarshal MySQL datetime to time.Time
- 利用logstash-output-jdbc从mysql导入数据到es中,如何构建多级节点的JSON
- MySql 5.7 json数据格式 增删改查 操作 (不定时更新)
- golang获取数据表转换为json通用方法
- mysql 查询JSON类型数据
- Python 输出JSON对象数组&写入数据到MySQL