Home  >  Article  >  Backend Development  >  How to use Go language for database operations

How to use Go language for database operations

WBOY
WBOYOriginal
2023-08-02 15:25:302915browse

How to use Go language for database operations

Introduction:
Go language is an efficient and concise programming language with powerful concurrency capabilities and excellent performance. In the development process, interaction with the database is a very important link. This article will introduce how to use Go language for database operations, including connecting to the database, CRUD operations, and transaction processing.

1. Connect to database
In Go language, we can use various database drivers to connect to different types of databases, such as MySQL, PostgreSQL, SQLite, etc. Taking MySQL as an example, you first need to install the MySQL driver. Just execute the following command on the command line:

go get github.com/go-sql-driver/mysql

Next, we can create a database connection pool to quickly obtain and release database connections. The sample code is as follows:

import (
    "database/sql"
    "fmt"

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

func main() {
    // 连接数据库
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/databaseName?charset=utf8")
    if err != nil {
        fmt.Println("数据库连接失败:", err)
        return
    }

    defer db.Close()

    // 测试连接是否成功
    err = db.Ping()
    if err != nil {
        fmt.Println("数据库连接失败:", err)
        return
    }

    fmt.Println("连接数据库成功!")
}

2. CRUD operation
The following is a common database operation sample code in Go language.

  1. Query data
func queryData(db *sql.DB) {
    rows, err := db.Query("SELECT id, name, age FROM users")
    if err != nil {
        fmt.Println("查询数据失败:", err)
        return
    }

    defer rows.Close()

    for rows.Next() {
        var id int
        var name string
        var age int
        err := rows.Scan(&id, &name, &age)
        if err != nil {
            fmt.Println("读取数据失败:", err)
            return
        }

        fmt.Println("ID:", id, "Name:", name, "Age:", age)
    }

    if err := rows.Err(); err != nil {
        fmt.Println("遍历数据失败:", err)
        return
    }
}
  1. Insert data
func insertData(db *sql.DB) {
    stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES(?, ?)")
    if err != nil {
        fmt.Println("插入数据失败:", err)
        return
    }

    defer stmt.Close()

    result, err := stmt.Exec("张三", 20)
    if err != nil {
        fmt.Println("插入数据失败:", err)
        return
    }

    rowAffected, err := result.RowsAffected()
    if err != nil {
        fmt.Println("获取影响的行数失败:", err)
        return
    }

    fmt.Println("成功插入", rowAffected, "行数据。")
}
  1. Update data
func updateData(db *sql.DB) {
    stmt, err := db.Prepare("UPDATE users SET age=? WHERE name=?")
    if err != nil {
        fmt.Println("更新数据失败:", err)
        return
    }

    defer stmt.Close()

    result, err := stmt.Exec(25, "张三")
    if err != nil {
        fmt.Println("更新数据失败:", err)
        return
    }

    rowAffected, err := result.RowsAffected()
    if err != nil {
        fmt.Println("获取影响的行数失败:", err)
        return
    }

    fmt.Println("成功更新", rowAffected, "行数据。")
}
  1. Delete data
func deleteData(db *sql.DB) {
    stmt, err := db.Prepare("DELETE FROM users WHERE name=?")
    if err != nil {
        fmt.Println("删除数据失败:", err)
        return
    }

    defer stmt.Close()

    result, err := stmt.Exec("张三")
    if err != nil {
        fmt.Println("删除数据失败:", err)
        return
    }

    rowAffected, err := result.RowsAffected()
    if err != nil {
        fmt.Println("获取影响的行数失败:", err)
        return
    }

    fmt.Println("成功删除", rowAffected, "行数据。")
}

3. Transaction processing
When performing database operations, sometimes it is necessary to ensure the atomicity of multiple operations, that is, either all succeed or all fail. At this time, transaction processing is needed. The sample code is as follows:

func transaction(db *sql.DB) {
    tx, err := db.Begin()
    if err != nil {
        fmt.Println("开启事务失败:", err)
        return
    }

    defer tx.Rollback()

    stmt, err := tx.Prepare("INSERT INTO users(name, age) VALUES(?, ?)")
    if err != nil {
        fmt.Println("插入数据失败:", err)
        return
    }

    defer stmt.Close()

    _, err = stmt.Exec("张三", 20)
    if err != nil {
        fmt.Println("插入数据失败:", err)
        return
    }

    stmt, err = tx.Prepare("UPDATE users SET age=? WHERE name=?")
    if err != nil {
        fmt.Println("更新数据失败:", err)
        return
    }

    defer stmt.Close()

    _, err = stmt.Exec(25, "张三")
    if err != nil {
        fmt.Println("更新数据失败:", err)
        return
    }

    err = tx.Commit()
    if err != nil {
        fmt.Println("提交事务失败:", err)
        return
    }

    fmt.Println("事务处理成功!")
}

Conclusion:
This article introduces how to use Go language for database operations, including connecting to the database, CRUD operations, and transaction processing. By studying these sample codes, I believe that everyone can better use the Go language to operate the database and improve the performance and efficiency of the program. Hope this article is helpful to everyone!

The above is the detailed content of How to use Go language for database operations. 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