Home > Database > Mysql Tutorial > body text

How to traverse mysql database in golang

王林
Release: 2023-06-03 12:55:26
forward
1163 people have browsed it

1. Connect to MySQL database

Before traversing the MySQL database, we need to establish a connection with the MySQL database first. Golang provides the database/sql package to make connecting to the MySQL database more convenient. First, we need to introduce this package:

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

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()
Copy after login

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)
Copy after login

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. We can use the Scan function to get the value of each field and return a row of data from the query results. 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)
}
Copy after login

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. You can use a for loop to traverse multiple rows of data in the query results, and use the Scan function to obtain the value of each field. 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)
    // 在此处可以对获取到的数据进行处理
}
Copy after login

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. Be sure to remember to use the Close function to close the query results. Once the processing is completed, the query results are no longer needed.

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

Related labels:
source:yisu.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!