Dumping MySQL tables to JSON with Golang

后端 未结 6 1954
余生分开走
余生分开走 2021-01-31 10:18

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 n

6条回答
  •  一整个雨季
    2021-01-31 10:53

    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.

提交回复
热议问题