Home >Backend Development >Golang >How golang traverses mysql

How golang traverses mysql

WBOY
WBOYOriginal
2023-05-15 10:08:07904browse

As the amount of data continues to increase, the MySQL database has become one of the most commonly used databases in modern application development. In applications, data processing often requires traversing and manipulating data, which requires the use of an efficient programming language. As a fast, simple, reliable and open source programming language, Golang is chosen by more and more developers to write applications.

This article will introduce how Golang traverses the MySQL database and related code implementation.

1. Connect to MySQL database

Before we start traversing the MySQL database, we need to connect to the MySQL database first. Golang provides the database/sql package for this purpose to facilitate our connection to the MySQL database. First, we need to introduce this package:

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

In order to connect to the MySQL database, we need to specify the database connection address, database name, account number, password and other information. The sample code is as follows:

db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database_name")
if err != nil {
    fmt.Println("连接数据库出错:", err)
    return
}
defer db.Close()

Among them, "mysql" is the driver name, the connection address is "127.0.0.1:3306", the database name is "database_name", and the account and password are "user" and "password".

After connecting to the database, we need to close the database connection at the end of the function. This can be achieved through the defer statement, as shown in the above code.

2. Query data

After connecting to the MySQL database, we can query the database. In Golang, there are two ways to perform query operations: one is to use the query function for single-row queries, and the other is to use the queryRows function for multi-row queries.

  1. Single row query

Single row query refers to querying one row of data in the database table. The sample code is as follows:

row := db.QueryRow("SELECT * FROM table_name WHERE id=?", 1)
if err != nil {
    fmt.Println("查询出错:", err)
    return
}
var id int
var name string
var age int
var address string
err = row.Scan(&id, &name, &age, &address)
if err != nil {
    fmt.Println("查询结果获取失败:", err)
    return
}
fmt.Println(id, name, age, address)

In the above code, we use the QueryRow function to query, where "?" is a placeholder, indicating the value of the query condition, in this case id=1. The query result will return a row of data, and we can obtain the value of each field through the Scan function. Finally, output the query results.

  1. Multi-row query

Multi-row query refers to querying multiple rows of data in the database table. The sample code is as follows:

rows, err := db.Query("SELECT * FROM table_name WHERE age > ?", 18)
if err != nil {
    fmt.Println("查询出错:", err)
    return
}
defer rows.Close()
for rows.Next() {
    var id int
    var name string
    var age int
    var address string
    err = rows.Scan(&id, &name, &age, &address)
    if err != nil {
        fmt.Println("查询结果获取失败:", err)
        return
    }
    fmt.Println(id, name, age, address)
}

In the above code, we use the Query function to query, where "?" is a placeholder, indicating the value of the query condition, in this case age>18. The query results will return multiple rows of data. We can traverse each row of data through a for loop, and then obtain the value of each field through the Scan function. Finally, output the query results.

3. Traverse MySQL data

After querying the data in the database table, we can traverse and process the data through a for loop. The sample code is as follows:

rows, err := db.Query("SELECT * FROM table_name")
if err != nil {
    fmt.Println("查询出错:", err)
    return
}
defer rows.Close()
for rows.Next() {
    var id int
    var name string
    var age int
    var address string
    err = rows.Scan(&id, &name, &age, &address)
    if err != nil {
        fmt.Println("查询结果获取失败:", err)
        return
    }
    fmt.Println(id, name, age, address)
    // 在此处可以对获取到的数据进行处理
}

In the above code, we first use the Query function to query all the data in the database table, then traverse each row of data through a for loop, and then obtain the value of each field through the Scan function. Finally, the obtained data is processed. After the processing is completed, if you no longer need to use the query results, you must remember to use the Close function to close the query results.

4. Summary

Through the above introduction, we can see that Golang’s connection and query operations for MySQL are very simple. With just a few lines of code, we can connect to the MySQL database and query and traverse the data in it. During the program development process, this will greatly reduce our workload and improve development efficiency. Therefore, Golang is gradually becoming one of the preferred programming languages ​​​​for most developers.

The above is the detailed content of How golang traverses mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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