golang: 把sql结果集以json格式输出

前端之家收集整理的这篇文章主要介绍了golang: 把sql结果集以json格式输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码出处:http://stackoverflow.com/questions/19991541/dumping-MysqL-tables-to-json-with-golang

func getJSON(sqlString string) (string,error) {
	stmt,err := db.Prepare(sqlString)
	if err != nil {
		return nil,err
	}
	defer stmt.Close()
	rows,err := stmt.Query()
	if err != nil {
		return nil,err
	}
	defer rows.Close()
	columns,err := rows.Columns()
	if err != nil {
	  return "",err
	}
	count := len(columns)
	tableData := make([]map[string]interface{},0)
	values := make([]interface{},count)
	valuePtrs := make([]interface{},count)
	for rows.Next() {
	  for i := 0; i < count; i++ {
		  valuePtrs[i] = &values[i]
	  }
	  rows.Scan(valuePtrs...)
	  entry := make(map[string]interface{})
	  for i,col := range columns {
		  var v interface{}
		  val := values[i]
		  b,ok := val.([]byte)
		  if ok {
			  v = string(b)
		  } else {
			  v = val
		  }
		  entry[col] = v
	  }
	  tableData = append(tableData,entry)
	}
	jsonData,err := json.Marshal(tableData)
	if err != nil {
	  return "",err
	}
	fmt.Println(string(jsonData))
	return string(jsonData),nil 
}

猜你在找的Go相关文章