使用Golang将MySQL表转储为JSON

huangapple go评论87阅读模式
英文:

Dumping MySQL tables to JSON with Golang

问题

我正在为Go语言编写一个快速的MySQL转JSON的转换器。然而,我发现从数据库中检索到的所有内容都是[]byte数组。因此,我得到的是将所有内容编码为字符串而不是原生的JSON整数或布尔值。

代码的一部分:

import (
    "encoding/json"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)


func dumpTable(w io.Writer, table) {
    // ...

    rows, err := Query(db, fmt.Sprintf("SELECT * FROM %s", table))
    checkError(err)
    columns, err := rows.Columns()
    checkError(err)

    scanArgs := make([]interface{}, len(columns))
    values   := make([]interface{}, len(columns))

    for i := range values {
        scanArgs[i] = &values[i]
    }

    for rows.Next() {
        err = rows.Scan(scanArgs...)
        checkError(err)

        record := make(map[string]interface{})

        for i, col := range values {
            if col != nil {
                fmt.Printf("\n%s: type= %s\n", columns[i], reflect.TypeOf(col))

                switch t := col.(type) {
                default:
                    fmt.Printf("Unexpected type %T\n", t)
                case bool:
                    fmt.Printf("bool\n")
                    record[columns[i]] = col.(bool)
                case int:
                    fmt.Printf("int\n")
                    record[columns[i]] = col.(int)
                case int64:
                    fmt.Printf("int64\n")
                    record[columns[i]] = col.(int64)
                case float64:
                    fmt.Printf("float64\n")
                    record[columns[i]] = col.(float64)
                case string:
                    fmt.Printf("string\n")
                    record[columns[i]] = col.(string)
                case []byte:   // -- 所有情况都在这里!
                    fmt.Printf("[]byte\n")
                    record[columns[i]] = string(col.([]byte))
                case time.Time:
                    // record[columns[i]] = col.(string)
                }
            }
        }

        s, _ := json.Marshal(record)
        w.Write(s)
        io.WriteString(w, "\n")
    }
}
英文:

Was putting together a quick dumper for MySQL to JSON in Go. However I find that everything that I retrieve from the database is a []byte array. Thus instead of native JSON integers or booleans, I'm getting everything encoded as strings.

Subset of the code:

import (
    "encoding/json"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)


func dumpTable(w io.Writer, table) {
    // ...

    rows, err := Query(db, fmt.Sprintf("SELECT * FROM %s", table))
    checkError(err)
    columns, err := rows.Columns()
    checkError(err)

    scanArgs := make([]interface{}, len(columns))
    values   := make([]interface{}, len(columns))

    for i := range values {
        scanArgs[i] = &values[i]
    }

    for rows.Next() {
        err = rows.Scan(scanArgs...)
        checkError(err)

        record := make(map[string]interface{})

        for i, col := range values {
            if col != nil {
                fmt.Printf("\n%s: type= %s\n", columns[i], reflect.TypeOf(col))

                switch t := col.(type) {
                default:
                    fmt.Printf("Unexpected type %T\n", t)
                case bool:
                    fmt.Printf("bool\n")
                    record[columns[i]] = col.(bool)
                case int:
                    fmt.Printf("int\n")
                    record[columns[i]] = col.(int)
                case int64:
                    fmt.Printf("int64\n")
                    record[columns[i]] = col.(int64)
                case float64:
                    fmt.Printf("float64\n")
                    record[columns[i]] = col.(float64)
                case string:
                    fmt.Printf("string\n")
                    record[columns[i]] = col.(string)
                case []byte:   // -- all cases go HERE!
                    fmt.Printf("[]byte\n")
                    record[columns[i]] = string(col.([]byte))
                case time.Time:
                    // record[columns[i]] = col.(string)
                }
            }
        }

        s, _ := json.Marshal(record)
        w.Write(s)
        io.WriteString(w, "\n")
    }
}

答案1

得分: 45

我也需要将数据库表转储为 JSON,以下是我实现的方法:
(与此主题中的另一个答案不同,这里不是所有的内容都是字符串,感谢这个答案:https://stackoverflow.com/a/17885636/4124416,我可以正确获取整数字段)

func getJSON(sqlString string) (string, error) {
    rows, err := db.Query(sqlString)
    if err != nil {
        return "", 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
}

这是一个示例输出:

[{"ID":0,"Text":"Zero"},{"ID":1,"Text":"One"},{"ID":2,"Text":"Two"}]
英文:

I also needed to dump database tables to json and here is how I achieved:
(different than another answer in this topic, everything is not string, thanks to this answer: https://stackoverflow.com/a/17885636/4124416, I could get integer fields correctly)

func getJSON(sqlString string) (string, error) {
    rows, err := db.Query(sqlString)
    if err != nil {
  	    return &quot;&quot;, err
    }
    defer rows.Close()
    columns, err := rows.Columns()
    if err != nil {
	    return &quot;&quot;, 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 &lt; count; i++ {
		  valuePtrs[i] = &amp;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 &quot;&quot;, err
    }
    fmt.Println(string(jsonData))
    return string(jsonData), nil 
}

Here is a sample output:

[{&quot;ID&quot;:0,&quot;Text&quot;:&quot;Zero&quot;},{&quot;ID&quot;:1,&quot;Text&quot;:&quot;One&quot;},{&quot;ID&quot;:2,&quot;Text&quot;:&quot;Two&quot;}]

答案2

得分: 3

需要使用预处理语句来获取原生类型。MySQL有两种协议,一种将所有内容都作为文本传输,另一种作为“真实”类型传输。而且只有在使用预处理语句时才会使用二进制协议。请参考https://github.com/go-sql-driver/mysql/issues/407。

下面的getJSON函数是正确的:

func getJSON(sqlString string) (string, error) {
  stmt, err := db.Prepare(sqlString)
  if err != nil {
    return "", err
  }
  defer stmt.Close()
   
  rows, err := stmt.Query()
  if err != nil {
    return "", err
  }
  defer rows.Close()

  columns, err := rows.Columns()
  if err != nil {
    return "", err
  }
  
  tableData := make([]map[string]interface{}, 0)
  
  count := len(columns)
  values := make([]interface{}, count)
  scanArgs := make([]interface{}, count)
  for i := range values {
    scanArgs[i] = &values[i]
  }
  
  for rows.Next() {
    err := rows.Scan(scanArgs...)
    if err != nil {
      return "", err
    }
    
    entry := make(map[string]interface{})
    for i, col := range columns {
      v := values[i]

      b, ok := v.([]byte)
      if ok {
        entry[col] = string(b)
      } else {
        entry[col] = v
      }
    }
  
    tableData = append(tableData, entry)
  }

  jsonData, err := json.Marshal(tableData)
  if err != nil {
    return "", err
  }

  return string(jsonData), nil 
}

以上是翻译好的内容。

英文:

It is needed to use prepared statements to get the native types. MySQL has two protocols, one transmits everything as text, the other as the "real" type. And that binary protocol is only used when you use prepared statements. See https://github.com/go-sql-driver/mysql/issues/407

The function getJSON below is correct:

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

答案3

得分: 2

由于driver - database/sql之间的交互基本上是单向的,当数据交给database/sql后,驱动程序无法帮助您解决任何问题,所以您没有太多可以做的。

您可以尝试使用http://godoc.org/github.com/arnehormann/sqlinternals/mysqlinternals。

  • 查询数据库
  • 使用cols, err := mysqlinternals.Columns(rows)检索列切片
  • 创建一个新的变量values := make([]interface{}, len(cols)),并遍历cols
  • 使用refType, err := cols[i].ReflectGoType()获取每列最匹配的Go类型
  • 使用values[i] = reflect.Zero(refType).Interface()创建类型占位符
  • rows.Next()err = rows.Scan(values...)。不要重新创建values,复制并重用它。

我猜这仍然会相当慢,但您应该能够有所进展。如果遇到问题,请提交一个问题 - 我会尽快解决。

英文:

There's not much you can do because the driver - database/sql interaction is pretty much a one way street and the driver can't help you with anything when the data is handed over to database/sql.

You could try your luck with http://godoc.org/github.com/arnehormann/sqlinternals/mysqlinternals

  • Query the database
  • Retrieve the Column slice with cols, err := mysqlinternals.Columns(rows)
  • Create a new var values := make([]interface{}, len(cols)) and iterate over cols
  • Get the closest matching Go type per column with refType, err := cols[i].ReflectGoType()
  • Create type placeholders with values[i] = reflect.Zero(refType).Interface()
  • rows.Next() and err = rows.Scan(values...). Don't recreate values, copy and reuse it.

I guess this will still be pretty slow, but you should be able to get somewhere with it.
If you encounter problems, please file an issue - I'll get to it as soon as I can.

答案4

得分: 2

我有一个名为practice_db的数据库中的名为users的表。我在下面的程序中提到了带有数据的表结构,该程序将users表转换为JSON格式。

你也可以在https://gist.github.com/hygull/1725442b0f121a5fc17b28e04796714d上查看源代码。

/**
	{
		"created_on": "26 may 2017",
		"todos": [
			"go get github.com/go-sql-driver/mysql",
			"postman(optional)",
			"browser(optional)",	
		],
		"aim": "Reading fname column into []string(slice of strings)"
	}
*/


/* 
	mysql> select * from users;
	+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
	| id | fname     | lname    | uname    | email                         | contact      | profile_pic                                                                                     |
	+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
	|  1 | Rishikesh | Agrawani | hygull   | rishikesh0014051992@gmail.com | 917353787704 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/user_group_users_accounts_contacts-512.png |
	|  2 | Sandeep   | E        | sandeep  | sandeepeswar8@gmail.com       | 919739040038 | https://cdn4.iconfinder.com/data/icons/eldorado-user/40/user-512.png                            |
	|  3 | Darshan   | Sidar    | darshan  | sidardarshan@gmail.com        | 917996917565 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/child_boy-512.png                          |
	|  4 | Surendra  | Prajapat | surendra | surendrakgadwal@gmail.com     | 918385894407 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/account_male-512.png                       |
	|  5 | Mukesh    | Jakhar   | mukesh   | mjakhar.kjakhar@gmail.com     | 919772254140 | https://cdn2.iconfinder.com/data/icons/rcons-user/32/male-circle-512.png                        |
	+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
	5 rows in set (0.00 sec)

	mysql> 
*/

package main

import "log"
import "net/http"
import "encoding/json"

import (
	_"github.com/go-sql-driver/mysql"	
	"database/sql"
)

func users(w http.ResponseWriter, r *http.Request) {
	// db, err := sql.Open("mysql", "<username>:<password>@tcp(127.0.0.1:<port>)/<dbname>?charset=utf8	")
	db, err := sql.Open("mysql", "hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8")

	w.Header().Set("Content-Type", "application/json")

	if err != nil {
		log.Fatal(err)
	}

	rows, err := db.Query("select id, fname, lname, uname, email, contact, profile_pic from users")

	if err != nil {
		log.Fatal(err)
	}

	type User struct {
		Id int 		 `json:"id"`
		Fname string `json:"firstname"`
		Lname string `json:"lastname"`
		Uname string `json:"username"`
		Email string `json:"email"`
		Contact int `json:"contact"`
		ProfilePic string `json:"profile_pic"`
	}
		
	var users []User

	for rows.Next() {
		var id, contact int
		var fname string
		var lname string
		var uname, email, profile_pic string

		rows.Scan(&id ,&fname, &lname, &uname, &email, &contact, &profile_pic)
		users = append(users, User{id, fname, lname, uname, email, contact, &profile_pic })
	}
	
	usersBytes, _ := json.Marshal(&users)
	
	w.Write(usersBytes)
	db.Close()
}

func main() {
	http.HandleFunc("/users/", users)
	http.ListenAndServe(":8080", nil)
}

/* REQUSET

   http://127.0.0.1:8080/users/
*/

/* RESPONSE
[
  {
    "id": 1,
    "firstname": "Rishikesh",
    "lastname": "Agrawani",
    "username": "hygull",
    "email": "rishikesh0014051992@gmail.com",
    "contact": 917353787704,
    "profile_pic": "https://cdn4.iconfinder.com/data/icons/rcons-user/32/user_group_users_accounts_contacts-512.png"
  },
  {
    "id": 2,
    "firstname": "Sandeep",
    "lastname": "E",
    "username": "sandeep",
    "email": "sandeepeswar8@gmail.com",
    "contact": 919739040038,
    "profile_pic": "https://cdn4.iconfinder.com/data/icons/eldorado-user/40/user-512.png"
  },
  {
    "id": 3,
    "firstname": "Darshan",
    "lastname": "Sidar",
    "username": "darshan",
    "email": "sidardarshan@gmail.com",
    "contact": 917996917565,
    "profile_pic": "https://cdn4.iconfinder.com/data/icons/rcons-user/32/child_boy-512.png"
  },
  {
    "id": 4,
    "firstname": "Surendra",
    "lastname": "Prajapat",
    "username": "surendra",
    "email": "surendrakgadwal@gmail.com",
    "contact": 918385894407,
    "profile_pic": "https://cdn4.iconfinder.com/data/icons/rcons-user/32/account_male-512.png"
  },
  {
    "id": 5,
    "firstname": "Mukesh",
    "lastname": "Jakhar",
    "username": "mukesh",
    "email": "mjakhar.kjakhar@gmail.com",
    "contact": 919772254140,
    "profile_pic": "https://cdn2.iconfinder.com/data/icons/rcons-user/32/male-circle-512.png"
  }
]
英文:

I have a table named users inside practice_db database. I have mentioned the table structure with data in the following program that converts the users table into JSON format.

You can also check the source code at https://gist.github.com/hygull/1725442b0f121a5fc17b28e04796714d.

/**
{
&quot;created_on&quot;: &quot;26 may 2017&quot;,
&quot;todos&quot;: [
&quot;go get github.com/go-sql-driver/mysql&quot;,
&quot;postman(optional)&quot;,
&quot;browser(optional)&quot;,	
],
&quot;aim&quot;: &quot;Reading fname column into []string(slice of strings)&quot;
}
*/
/* 
mysql&gt; select * from users;
+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
| id | fname     | lname    | uname    | email                         | contact      | profile_pic                                                                                     |
+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
|  1 | Rishikesh | Agrawani | hygull   | rishikesh0014051992@gmail.com | 917353787704 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/user_group_users_accounts_contacts-512.png |
|  2 | Sandeep   | E        | sandeep  | sandeepeswar8@gmail.com       | 919739040038 | https://cdn4.iconfinder.com/data/icons/eldorado-user/40/user-512.png                            |
|  3 | Darshan   | Sidar    | darshan  | sidardarshan@gmail.com        | 917996917565 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/child_boy-512.png                          |
|  4 | Surendra  | Prajapat | surendra | surendrakgadwal@gmail.com     | 918385894407 | https://cdn4.iconfinder.com/data/icons/rcons-user/32/account_male-512.png                       |
|  5 | Mukesh    | Jakhar   | mukesh   | mjakhar.kjakhar@gmail.com     | 919772254140 | https://cdn2.iconfinder.com/data/icons/rcons-user/32/male-circle-512.png                        |
+----+-----------+----------+----------+-------------------------------+--------------+-------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)
mysql&gt; 
*/
package main
import &quot;log&quot;
import &quot;net/http&quot;
import &quot;encoding/json&quot;
import (
_&quot;github.com/go-sql-driver/mysql&quot;	
&quot;database/sql&quot;
)
func users(w http.ResponseWriter, r *http.Request) {
// db, err := sql.Open(&quot;mysql&quot;, &quot;&lt;username&gt;:&lt;password&gt;@tcp(127.0.0.1:&lt;port&gt;)/&lt;dbname&gt;?charset=utf8&quot;	)
db, err := sql.Open(&quot;mysql&quot;, &quot;hygull:admin@67@tcp(127.0.0.1:3306)/practice_db?charset=utf8&quot;)
w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
if err != nil {
log.Fatal(err)
}
rows, err := db.Query(&quot;select id, fname, lname, uname, email, contact, profile_pic from users&quot;)
if err != nil {
log.Fatal(err)
}
type User struct {
Id int 		 `json:&quot;id&quot;`
Fname string `json:&quot;firstname&quot;`
Lname string `json:&quot;lastname&quot;`
Uname string `json:&quot;username&quot;`
Email string `json:&quot;email&quot;`
Contact int `json:&quot;contact&quot;`
ProfilePic string `json:&quot;profile_pic&quot;`
}
var users []User
for rows.Next() {
var id, contact int
var fname string
var lname string
var uname, email, profile_pic string
rows.Scan(&amp;id ,&amp;fname, &amp;lname, &amp;uname, &amp;email, &amp;contact, &amp;profile_pic)
users = append(users, User{id, fname, lname, uname, email, contact, &amp;profile_pic })
}
usersBytes, _ := json.Marshal(&amp;users)
w.Write(usersBytes)
db.Close()
}
func main() {
http.HandleFunc(&quot;/users/&quot;, users)
http.ListenAndServe(&quot;:8080&quot;, nil)
}
/* REQUSET
http://127.0.0.1:8080/users/
*/
/* RESPONSE
[
{
&quot;id&quot;: 1,
&quot;firstname&quot;: &quot;Rishikesh&quot;,
&quot;lastname&quot;: &quot;Agrawani&quot;,
&quot;username&quot;: &quot;hygull&quot;,
&quot;email&quot;: &quot;rishikesh0014051992@gmail.com&quot;,
&quot;contact&quot;: 917353787704,
&quot;profile_pic&quot;: &quot;https://cdn4.iconfinder.com/data/icons/rcons-user/32/user_group_users_accounts_contacts-512.png&quot;
},
{
&quot;id&quot;: 2,
&quot;firstname&quot;: &quot;Sandeep&quot;,
&quot;lastname&quot;: &quot;E&quot;,
&quot;username&quot;: &quot;sandeep&quot;,
&quot;email&quot;: &quot;sandeepeswar8@gmail.com&quot;,
&quot;contact&quot;: 919739040038,
&quot;profile_pic&quot;: &quot;https://cdn4.iconfinder.com/data/icons/eldorado-user/40/user-512.png&quot;
},
{
&quot;id&quot;: 3,
&quot;firstname&quot;: &quot;Darshan&quot;,
&quot;lastname&quot;: &quot;Sidar&quot;,
&quot;username&quot;: &quot;darshan&quot;,
&quot;email&quot;: &quot;sidardarshan@gmail.com&quot;,
&quot;contact&quot;: 917996917565,
&quot;profile_pic&quot;: &quot;https://cdn4.iconfinder.com/data/icons/rcons-user/32/child_boy-512.png&quot;
},
{
&quot;id&quot;: 4,
&quot;firstname&quot;: &quot;Surendra&quot;,
&quot;lastname&quot;: &quot;Prajapat&quot;,
&quot;username&quot;: &quot;surendra&quot;,
&quot;email&quot;: &quot;surendrakgadwal@gmail.com&quot;,
&quot;contact&quot;: 918385894407,
&quot;profile_pic&quot;: &quot;https://cdn4.iconfinder.com/data/icons/rcons-user/32/account_male-512.png&quot;
},
{
&quot;id&quot;: 5,
&quot;firstname&quot;: &quot;Mukesh&quot;,
&quot;lastname&quot;: &quot;Jakhar&quot;,
&quot;username&quot;: &quot;mukesh&quot;,
&quot;email&quot;: &quot;mjakhar.kjakhar@gmail.com&quot;,
&quot;contact&quot;: 919772254140,
&quot;profile_pic&quot;: &quot;https://cdn2.iconfinder.com/data/icons/rcons-user/32/male-circle-512.png&quot;
}
]
*/

答案5

得分: 0

根据这里的答案,这是我能想到的最高效的代码。请注意,这将每一行输出为单独的JSON数组,以节省键名的重复。

// OutputJSONMysqlRowsStream 将行作为JSON数组流输出,以节省内存和输出大小
func OutputJSONMysqlRowsStream(writer http.ResponseWriter, rows *sql.Rows) {

	defer rows.Close()

	columns, err := rows.Columns()

	if err != nil {
		OutputJSONError(writer, "获取列名失败")
		return
	}

	jsonColumns, err := json.Marshal(columns)

	if err != nil {
		OutputJSONError(writer, "编码列名的JSON失败")
		return
	}

	writer.Header().Set("Content-Type", "application/cal-json-stream; charset=utf-8")

	fmt.Fprintln(writer, `{"status": "done", "data":{"json_stream_fields":`+string(jsonColumns)+`}}`)

	columnCount := len(columns)
	rowDataHolder := make([]interface{}, columnCount)
	rowDataHolderPointers := make([]interface{}, columnCount)

	if err != nil {
		log.Println(err)
	}

	for rows.Next() {

		for i := 0; i < columnCount; i++ {
			rowDataHolderPointers[i] = &rowDataHolder[i]
		}

		err := rows.Scan(rowDataHolderPointers...)

		if err != nil {
			log.Println(err)
		} else {

			for i, value := range rowDataHolder {
				tempValue, ok := value.([]byte)

				if ok {
					rowDataHolder[i] = string(tempValue)
				}
			}

			jsonEncoder := json.NewEncoder(writer)
			err = jsonEncoder.Encode(rowDataHolder)

			if err != nil {
				log.Println(err)
			}
		}
	}
}

以上是翻译好的代码部分。

英文:

Based on the answers here, this is the most efficient code I could come up with. Note that this is outputting each row as a separate JSON array to save key name repetition.

// OutputJSONMysqlRowsStream outputs rows as a JSON array stream to save ram &amp; output size due to key name repetition
func OutputJSONMysqlRowsStream(writer http.ResponseWriter, rows *sql.Rows) {
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
OutputJSONError(writer, &quot;Failed to get column names&quot;)
return
}
jsonColumns, err := json.Marshal(columns)
if err != nil {
OutputJSONError(writer, &quot;Failed to encode json of column names&quot;)
return
}
writer.Header().Set(&quot;Content-Type&quot;, &quot;application/cal-json-stream; charset=utf-8&quot;)
fmt.Fprintln(writer, &quot;{\&quot;status\&quot;: \&quot;done\&quot;, \&quot;data\&quot;:{ \&quot;json_stream_fields\&quot;:&quot;+string(jsonColumns)+&quot;}}&quot;)
columnCount := len(columns)
rowDataHolder := make([]interface{}, columnCount)
rowDataHolderPointers := make([]interface{}, columnCount)
if err != nil {
log.Println(err)
}
for rows.Next() {
for i := 0; i &lt; columnCount; i++ {
rowDataHolderPointers[i] = &amp;rowDataHolder[i]
}
err := rows.Scan(rowDataHolderPointers...)
if err != nil {
log.Println(err)
} else {
for i, value := range rowDataHolder {
tempValue, ok := value.([]byte)
if ok {
rowDataHolder[i] = string(tempValue)
}
}
jsonEncoder := json.NewEncoder(writer)
err = jsonEncoder.Encode(rowDataHolder)
if err != nil {
log.Println(err)
}
}
}
}

答案6

得分: -1

你可以将表转储为 JSON,但是所有的数据都会被转换为字符串 使用Golang将MySQL表转储为JSON

q := "select * from table"
debug("SQL: %s", q)

rows, err := db.Query(q)
checkError(err)
defer rows.Close()

columns, err := rows.Columns()
checkError(err)

scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))

for i := range values {
    scanArgs[i] = &values[i]
}

for rows.Next() {
    err = rows.Scan(scanArgs...)
    checkError(err)

    record := make(map[string]interface{})

    for i, col := range values {
        if col != nil {
            record[columns[i]] = fmt.Sprintf("%s", string(col.([]byte)))
        }
    }

    s, _ := json.Marshal(record)
    fmt.Printf("%s\n", s)
}
英文:

you can dump the table into json just fine, however everything will be string 使用Golang将MySQL表转储为JSON

q := &quot;select * from table&quot;
debug(&quot;SQL: %s&quot;, q)
rows, err := db.Query(q)
checkError(err)
defer rows.Close()
columns, err := rows.Columns()
checkError(err)
scanArgs := make([]interface{}, len(columns))
values := make([]interface{}, len(columns))
for i := range values {
scanArgs[i] = &amp;values[i]
}
for rows.Next() {
err = rows.Scan(scanArgs...)
checkError(err)
record := make(map[string]interface{})
for i, col := range values {
if col != nil {
record[columns[i]] = fmt.Sprintf(&quot;%s&quot;, string(col.([]byte)))
}
}
s, _ := json.Marshal(record)
fmt.Printf(&quot;%s\n&quot;, s)
}

huangapple
  • 本文由 发表于 2013年11月15日 08:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/19991541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定