Home >Backend Development >Golang >Go language practice: using MySQL to store data

Go language practice: using MySQL to store data

WBOY
WBOYOriginal
2023-06-18 23:49:401033browse

With the rapid development of the Internet, the storage and processing of large amounts of data has become an inevitable trend. As an open source and easy-to-use database system, the relational database MySQL is often used to store application data. This article will introduce how to use Go language to interact with MySQL, store and query data.

  1. Environment setup
    First you need to install the Go language and MySQL database. You can use the following command to install:

    go get -u github.com/go-sql-driver/mysql
  2. Database connection
    Before using MySQL, you need to ensure that the MySQL service has been installed and started. You can use the following command to connect:

    db, err := sql.Open("mysql", "username:password@tcp(host:port)/dbname")

    Among them, username and password are the username and password of the database respectively, host and port are the IP address and port of the MySQL server respectively. number, dbname is the name of the database to be connected.

  3. Database Operation
    Next, you can perform CRUD operations on the database. The following are commonly used MySQL operation commands in Go language:
    (1) Query data

    rows, err := db.Query("SELECT * FROM table_name")
    defer rows.Close()
    for rows.Next() {
     // 查询结果
    }

    (2) Insert data

    stmt, err := db.Prepare("INSERT INTO table_name (col1, col2) VALUES (?, ?)")
    _, err = stmt.Exec(val1, val2)

    (3) Update data

    stmt, err := db.Prepare("UPDATE table_name SET col1 = ? WHERE col2 = ?")
    _, err = stmt.Exec(val1, val2)

    ( 4) Delete data

    stmt, err := db.Prepare("DELETE FROM table_name WHERE col1 = ?")
    _, err = stmt.Exec(val)
  4. Complete example
    The following is a complete example of using Go language to interact with MySQL:

    package main
    
    import (
     "database/sql"
     "fmt"
     _ "github.com/go-sql-driver/mysql"
    )
    
    func main() {
     db, err := sql.Open("mysql", "username:password@tcp(host:port)/dbname")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
     defer db.Close()
    
     // 查询数据
     rows, err := db.Query("SELECT * FROM table_name")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
     defer rows.Close()
     for rows.Next() {
         var id int
         var name string
         if err := rows.Scan(&id, &name); err != nil {
             fmt.Println(err.Error())
             return
         }
         fmt.Printf("id: %d, name: %s
    ", id, name)
     }
    
     // 插入数据
     stmt, err := db.Prepare("INSERT INTO table_name (id, name) VALUES (?, ?)")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
     defer stmt.Close()
     _, err = stmt.Exec(1, "test")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
    
     // 更新数据
     stmt, err = db.Prepare("UPDATE table_name SET name = ? WHERE id = ?")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
     defer stmt.Close()
     _, err = stmt.Exec("updated_test", 1)
     if err != nil {
         fmt.Println(err.Error())
         return
     }
    
     // 删除数据
     stmt, err = db.Prepare("DELETE FROM table_name WHERE id = ?")
     if err != nil {
         fmt.Println(err.Error())
         return
     }
     defer stmt.Close()
     _, err = stmt.Exec(1)
     if err != nil {
         fmt.Println(err.Error())
         return
     }
    }
  5. Summary
    Through the above examples, we can see that it is very convenient and easy to use Go language to interact with MySQL. Operating databases is something that every developer often needs to do during development. Mastering the interaction between Go language and MySQL is very helpful for developing and maintaining applications.

The above is the detailed content of Go language practice: using MySQL to store data. 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