How to save JSON data to database in Golang?

PHPz
Release: 2024-06-06 11:24:57
Original
710 people have browsed it

JSON data can be saved to a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods for parsing JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

如何在 Golang 中将 JSON 数据保存到数据库中?

How to save JSON data to the database in Golang

Introduction
In Golang , saving JSON data to a database is a common task. This article will explore different methods of persisting JSON data using commonly used databases such as MySQL, and provide practical examples for reference.

Using the gjson library
The gjson library is a popular Golang package for parsing and manipulating JSON data. It provides easy methods to parse JSON data into Go data structures such as maps and slices.

package main

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

func main() {
    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    jsonData := `{
        "name": "John Doe",
        "age": 30,
        "address": {
            "street": "Main Street",
            "city": "New York"
        }
    }`

    values := []interface{}{}

    // 解析 JSON 字段
    name := gjson.Get(jsonData, "name").String()
    age := gjson.Get(jsonData, "age").Int()
    address := gjson.Get(jsonData, "address").String()

    values = append(values, name, age, address)

    // 准备 SQL 语句
    stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)")
    if err != nil {
        panic(err)
    }

    // 执行插入操作
    _, err = stmt.Exec(values...)
    if err != nil {
        panic(err)
    }

    fmt.Println("JSON data saved to database successfully")
}
Copy after login

Using json.Unmarshal
The json.Unmarshal function is part of the Golang standard library and is used to unmarshal JSON data into Go variables. This method requires a target type pointer as the second parameter.

package main

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

func main() {
    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    jsonData := `{
        "name": "John Doe",
        "age": 30,
        "address": {
            "street": "Main Street",
            "city": "New York"
        }
    }`

    var user struct {
        Name     string
        Age      int
        Address  string
    }

    err = json.Unmarshal([]byte(jsonData), &user)
    if err != nil {
        panic(err)
    }

    // 准备 SQL 语句
    stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)")
    if err != nil {
        panic(err)
    }

    // 执行插入操作
    _, err = stmt.Exec(user.Name, user.Age, user.Address)
    if err != nil {
        panic(err)
    }

    fmt.Println("JSON data saved to database successfully")
}
Copy after login

The above is the detailed content of How to save JSON data to database in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template