亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development Golang How to save JSON data to database in Golang?

How to save JSON data to database in Golang?

Jun 06, 2024 am 11:24 AM
json golang database

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 數(shù)據(jù)保存到數(shù)據(jù)庫中?

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)

    // 準(zhǔn)備 SQL 語句
    stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)")
    if err != nil {
        panic(err)
    }

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

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

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)
    }

    // 準(zhǔn)備 SQL 語句
    stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)")
    if err != nil {
        panic(err)
    }

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

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

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Strategies for Integrating Golang Services with Existing Python Infrastructure Strategies for Integrating Golang Services with Existing Python Infrastructure Jul 02, 2025 pm 04:39 PM

TointegrateGolangserviceswithexistingPythoninfrastructure,useRESTAPIsorgRPCforinter-servicecommunication,allowingGoandPythonappstointeractseamlesslythroughstandardizedprotocols.1.UseRESTAPIs(viaframeworkslikeGininGoandFlaskinPython)orgRPC(withProtoco

Understanding the Performance Differences Between Golang and Python for Web APIs Understanding the Performance Differences Between Golang and Python for Web APIs Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

Redis vs databases: what are the limits? Redis vs databases: what are the limits? Jul 02, 2025 am 12:03 AM

Redisislimitedbymemoryconstraintsanddatapersistence,whiletraditionaldatabasesstrugglewithperformanceinreal-timescenarios.1)Redisexcelsinreal-timedataprocessingandcachingbutmayrequirecomplexshardingforlargedatasets.2)TraditionaldatabaseslikeMySQLorPos

What is the significance of the Oracle instance, and how does it relate to the database? What is the significance of the Oracle instance, and how does it relate to the database? Jun 28, 2025 am 12:01 AM

AnOracleinstanceistheruntimeenvironmentthatenablesaccesstoanOracledatabase.Itcomprisestwomaincomponents:theSystemGlobalArea(SGA)andbackgroundprocesses.1.TheSGAincludesthedatabasebuffercache,redologbuffer,andsharedpool,whichmanagedataandSQLstatements.

Access nested JSON object in Python Access nested JSON object in Python Jul 11, 2025 am 02:36 AM

The way to access nested JSON objects in Python is to first clarify the structure and then index layer by layer. First, confirm the hierarchical relationship of JSON, such as a dictionary nested dictionary or list; then use dictionary keys and list index to access layer by layer, such as data "details"["zip"] to obtain zip encoding, data "details"[0] to obtain the first hobby; to avoid KeyError and IndexError, the default value can be set by the .get() method, or the encapsulation function safe_get can be used to achieve secure access; for complex structures, recursively search or use third-party libraries such as jmespath to handle.

How to work with JSON data in Python? How to work with JSON data in Python? Jul 03, 2025 am 02:11 AM

Processing JSON data is very common in Python, especially when interacting with network requests and APIs. The following are common operations: 1. Use json.loads() to parse JSON strings into Python objects (such as dictionaries or lists), which is suitable for processing after obtaining data from the API; 2. Use json.dumps() to serialize Python objects into JSON strings, which is suitable for sending data or saving configuration files, and can optimize the output format through indent and ensure_ascii parameters; 3. Use json.load() and json.dump() to read and write JSON files respectively, which is suitable for processing local configuration or batch data; pay attention to load

How to convert json string to php array? How to convert json string to php array? Jul 02, 2025 pm 04:48 PM

Use the json_decode function and set the second parameter to true to convert the JSON string to PHP array; 1. The usage is $array=json_decode($jsonString,true); 2. If the second parameter is not added, the stdClass object will be returned; 3. Make sure that the input string is valid JSON, otherwise it will return null; 4. You can check errors through json_last_error(); 5. Common errors include format problems such as unclosed quotes, redundant commas, etc.; 6. After the conversion in the example, you can access the corresponding value through the array key; as long as you pay attention to the format and parameter settings, the conversion can be completed smoothly.

How to select a different database in Redis? How to select a different database in Redis? Jul 05, 2025 am 12:16 AM

ToswitchdatabasesinRedis,usetheSELECTcommandfollowedbythenumericindex.Redissupportsmultiplelogicaldatabases(default16),andeachclientconnectionmaintainsitsownselecteddatabase.1.UseSELECTindex(e.g.,SELECT2)toswitchtoanotherdatabase.2.Verifywithcommands

See all articles