--Je veux convertir la requête entière obtenue par l'instruction SELECT en JSON --Il semble que l'analyse du package sql est en cours de traitement ligne par ligne, et vous devez créer un tableau dans la boucle (?) --Convertir à partir du tableau avec le package json
main.go
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/lib/pq"
)
const (
// Initialize connection constants.
HOST = "127.0.0.1"
DATABASE = "testdb"
USER = "root"
PASSWORD = "password"
)
func checkError(err error) {
if err != nil {
panic(err)
}
}
func main() {
// Initialize connection string.
var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", HOST, USER, PASSWORD, DATABASE)
// Initialize connection object.
db, err := sql.Open("postgres", connectionString)
checkError(err)
err = db.Ping()
checkError(err)
fmt.Println("Successfully created connection to database")
// Read rows from table.
var id int
var name string
var quantity int
sql_statement := "SELECT * from inventory;"
rows, err := db.Query(sql_statement)
checkError(err)
defer rows.Close()
//Définir la structure
type data struct {
ID int
Name string
Quantity int
}
//Déclarez le type de tableau
var fruit []data
for rows.Next() {
switch err := rows.Scan(&id, &name, &quantity); err {
case sql.ErrNoRows:
fmt.Println("No rows were returned")
case nil:
fmt.Printf("Data row = (%d, %s, %d)\n", id, name, quantity)
//Ajouter un tableau ligne par ligne
fruit = append(fruit,data{
ID: id,
Name: name,
Quantity: quantity,
})
default:
checkError(err)
}
}
fruitjson, _ := json.Marshal(fruit)
fmt.Println(string(fruitjson))
}
yuta:~/postgre $ go run main.go
Successfully created connection to database
Data row = (1, banana, 150)
Data row = (2, orange, 154)
Data row = (3, apple, 100)
Data row = (4, test, 100)
[{"ID":1,"Name":"banana","Quantity":150},{"ID":2,"Name":"orange","Quantity":154},{"ID":3,"Name":"apple","Quantity":100},{"ID":4,"Name":"test","Quantity":100}]
https://docs.microsoft.com/ja-jp/azure/postgresql/connect-go
Recommended Posts