Home Backend Development Golang How to add data in golang

How to add data in golang

Mar 30, 2023 am 09:06 AM

Go language is a programming language that has become more popular in recent years. In development, we often need to use data to add this function. So, how to add data in golang? This article will introduce you to the method of adding data in golang in detail.

1. Add elements to the list

In Golang, lists (also called slices) are a very commonly used data type. To add elements to a list, you can use the append() function. This function is a bit like the append() function in Python. For example:

list := []string{"apple", "banana", "orange"}
list = append(list, "pear")
fmt.Println(list)
Copy after login

Execute the above code, the output result is:

[apple banana orange pear]
Copy after login

You can see that after using the append() function, pear is added to the end of the list (string array).

2. Add key-value pairs to dictionary

Dictionary (also called map) is another common data type in Golang. To add key-value pairs to the dictionary, you can use the following syntax:

m := make(map[string]string)
m["name"] = "Tom"
m["age"] = "18"
Copy after login

In the above example, the make() function is used to create an empty dictionary. Then, we can add key-value pairs to the dictionary using the form m["key"] = value. In particular, it is important to note that the keys and values ​​in the dictionary must be of the same data type.

3. Add CSV data

In Golang, you can also add data in CSV (Comma-Separated Values) format. CSV data can be read and written using the encoding/csv package. Here is an example that demonstrates how to write data to a CSV file:

package main

import (
    "encoding/csv"
    "os"
)

func main() {
    file, err := os.Create("data.csv")
    if err != nil {
        panic(err)
    }

    writer := csv.NewWriter(file)
    defer writer.Flush()

    writer.Write([]string{"name", "age", "gender"})
    writer.Write([]string{"Tom", "18", "Male"})
    writer.Write([]string{"Lily", "20", "Female"})
}
Copy after login

In the above code, we first create a file named data.csv. Then, a CSV writer (writer) was created, the writer.Write() method was called, and three rows of data were written in sequence. Finally, we use the defer keyword to ensure that the writer.Flush() method will be executed and the data in the cache will be written to the file before the main() function returns.

4. Add MySQL data

How to add MySQL data in Golang? First, you need to use the database driver in the Go language. There are many ready-made MySQL database drivers in Golang. Here we choose the more popular third-party library-github.com/go-sql-driver/mysql.

We can add MySQL data in Golang according to the following syntax:

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

func main() {
    user := "root"
    password := "root"
    host := "localhost"
    port := "3306"
    database := "test"

    db, err := sql.Open("mysql", user+":"+password+"@tcp("+host+":"+port+")/"+database)
    if err != nil {
        panic(err)
    }

    defer db.Close()

    stmt, err := db.Prepare("INSERT INTO user(name, age, gender) VALUES(?, ?, ?)")
    if err != nil {
        panic(err)
    }

    res, err := stmt.Exec("Tom", 18, "Male")
    if err != nil {
        panic(err)
    }

    lastId, err := res.LastInsertId()
    if err != nil {
        panic(err)
    }

    fmt.Println("LastInsertId:", lastId)
}
Copy after login

In the above code, we first connect to the MySQL database through the sql.Open() function. Next, use the Prepare() method to preprocess the SQL statement. When executing the SQL statement, we can use the Exec() function to perform operations such as INSERT, UPDATE, and DELETE.

Finally, use the LastInsertId() method to get the ID of the record just inserted to ensure that we have successfully added data to the database.

Summary

This article introduces several methods of adding data in Golang, including adding elements to lists, adding key-value pairs to dictionaries, adding CSV data, and adding MySQL data. Of course, you can also use other methods to implement the data addition function, and the specific effect will depend on the actual situation. In short, Golang is a very flexible and efficient programming language that is widely used in daily development. I hope this article will be helpful to you.

The above is the detailed content of How to add data 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles