国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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)

    // 準備 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)
    }

    // 準備 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)

Redis: A Comparison to Traditional Database Servers Redis: A Comparison to Traditional Database Servers May 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

JSON vs. XML: Why RSS Chose XML JSON vs. XML: Why RSS Chose XML May 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

Is Redis Primarily a Database? Is Redis Primarily a Database? May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Learning SQL: Understanding the Challenges and Rewards Learning SQL: Understanding the Challenges and Rewards May 11, 2025 am 12:16 AM

Learning SQL requires mastering basic knowledge, core queries, complex JOIN operations and performance optimization. 1. Understand basic concepts such as tables, rows, and columns and different SQL dialects. 2. Proficient in using SELECT statements for querying. 3. Master the JOIN operation to obtain data from multiple tables. 4. Optimize query performance, avoid common errors, and use index and EXPLAIN commands.

sql database statements summary of common statements for sql database sql database statements summary of common statements for sql database May 28, 2025 pm 08:12 PM

Common SQL statements include: 1. CREATETABLE creates tables, such as CREATETABLEemployees(idINTPRIMARYKEY, nameVARCHAR(100), salaryDECIMAL(10,2)); 2. CREATEINDEX creates indexes, such as CREATEINDEXidx_nameONemployees(name); 3. INSERTINTO inserts data, such as INSERTINTO employeees(id, name, salary)VALUES(1,'JohnDoe',75000.00); 4. SELECT check

When Should I Use Redis Instead of a Traditional Database? When Should I Use Redis Instead of a Traditional Database? May 13, 2025 pm 04:01 PM

UseRedisinsteadofatraditionaldatabasewhenyourapplicationrequiresspeedandreal-timedataprocessing,suchasforcaching,sessionmanagement,orreal-timeanalytics.Redisexcelsin:1)Caching,reducingloadonprimarydatabases;2)Sessionmanagement,simplifyingdatahandling

How to view all databases in MongoDB How to view all databases in MongoDB Jun 04, 2025 pm 10:42 PM

The way to view all databases in MongoDB is to enter the command "showdbs". 1. This command only displays non-empty databases. 2. You can switch the database through the "use" command and insert data to make it display. 3. Pay attention to internal databases such as "local" and "config". 4. When using the driver, you need to use the "listDatabases()" method to obtain detailed information. 5. The "db.stats()" command can view detailed database statistics.

Oracle: Enterprise Software and Cloud Computing Oracle: Enterprise Software and Cloud Computing May 05, 2025 am 12:01 AM

Oracle is so important in the enterprise software and cloud computing sectors because of its comprehensive solutions and strong technical support. 1) Oracle provides a wide range of product lines from database management to ERP, 2) its cloud computing services such as OracleCloudPlatform and Infrastructure help enterprises achieve digital transformation, 3) Oracle database stability and performance and seamless integration of cloud services improve enterprise efficiency.

See all articles