Home > Backend Development > Golang > How to implement database operation functions in go language

How to implement database operation functions in go language

WBOY
Release: 2023-08-26 17:42:23
Original
972 people have browsed it

How to implement database operation functions in go language

How to implement database operation functions in Go language

As an efficient and concise programming language, Go language is very suitable for developing server backends and databases operate. In actual application development, database operation is an essential link. Today, we will introduce how to implement database operation functions in Go language, as well as some common operation examples.

1. Database connection

In Go language, we can use third-party libraries to connect to various types of databases. Among them, the most commonly used are the "database/sql" package in the standard library, and various database drivers, such as "go-sqlite3", "mysql" and "postgres".

First, we need to import the required packages:

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

Then, we can use the "sql.Open" function to connect to the database:

db, err := sql.Open("mysql", "user:password@tcp(localhost:8889)/mydb")
if err != nil {
    log.Fatal(err)
}
defer db.Close()
Copy after login

In the above code, We used the MySQL driver and specified the address and credentials for the database connection. If the connection is successful, we can perform various database operations through the "db" object.

2. Execute SQL statements

Generally speaking, database operations mainly include functions such as query, insert, update and delete. Below are some examples of common database operations.

  1. Query data
rows, err := db.Query("SELECT * FROM users")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    err := rows.Scan(&id, &name)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(id, name)
}

err = rows.Err()
if err != nil {
    log.Fatal(err)
}
Copy after login

In the above code, we executed a SELECT statement through the "db.Query" function and passed "rows.Next" and "rows .Scan" to obtain query results. It should be noted that we need to use "defer rows.Close()" to ensure that resources are released after using the query results.

  1. Insert data
stmt, err := db.Prepare("INSERT INTO users(name) VALUES(?)")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close()

res, err := stmt.Exec("John")
if err != nil {
    log.Fatal(err)
}

id, err := res.LastInsertId()
if err != nil {
    log.Fatal(err)
}

fmt.Println("Inserted record ID:", id)
Copy after login

In the above code, we use the "db.Prepare" function to prepare an INSERT statement and use "stmt.Exec" to perform the insert operate. Then, we can get the ID corresponding to the inserted record through "res.LastInsertId".

  1. Update data
stmt, err := db.Prepare("UPDATE users SET name=? WHERE id=?")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close()

res, err := stmt.Exec("John Smith", 1)
if err != nil {
    log.Fatal(err)
}

rowsAffected, err := res.RowsAffected()
if err != nil {
    log.Fatal(err)
}

fmt.Println("Rows affected:", rowsAffected)
Copy after login

In the above code, we prepared an UPDATE statement through the "db.Prepare" function and used "stmt.Exec" to perform the update operate. We can then get the number of affected rows via "res.RowsAffected".

  1. Delete data
stmt, err := db.Prepare("DELETE FROM users WHERE id=?")
if err != nil {
    log.Fatal(err)
}
defer stmt.Close()

res, err := stmt.Exec(1)
if err != nil {
    log.Fatal(err)
}

rowsAffected, err := res.RowsAffected()
if err != nil {
    log.Fatal(err)
}

fmt.Println("Rows affected:", rowsAffected)
Copy after login

In the above code, we prepared a DELETE statement through the "db.Prepare" function and used "stmt.Exec" to perform the delete operate. Similarly, we can get the number of affected rows through "res.RowsAffected".

3. Transaction processing

In practical application development, transaction processing is a very important function. In Go language, we can use "db.Begin" to start a transaction and "tx.Commit" to commit the transaction. If an error occurs during transaction processing, we can use "tx.Rollback" to roll back the transaction.

tx, err := db.Begin()
if err != nil {
    log.Fatal(err)
}

stmt, err := tx.Prepare("INSERT INTO users(name) VALUES(?)")
if err != nil {
    tx.Rollback()
    log.Fatal(err)
}
defer stmt.Close()

_, err = stmt.Exec("John")
if err != nil {
    tx.Rollback()
    log.Fatal(err)
}

err = tx.Commit()
if err != nil {
    log.Fatal(err)
}
Copy after login

In the above code, we use "db.Begin" to start a transaction and perform insert operations in the transaction. If an error occurs, we use "tx.Rollback" to roll back the transaction; otherwise, we use "tx.Commit" to commit the transaction.

Summary:

Through the introduction of this article, we have learned how to implement database operation functions in Go language and demonstrated some common database operation examples. It is worth mentioning that various types of databases can be easily connected using the "database/sql" package and appropriate database drivers. I hope this article will help you perform database operations in Go language!

The above is the detailed content of How to implement database operation functions in go language. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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