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

Go language practice: using MySQL to store data

Jun 18, 2023 pm 11:49 PM
mysql go language data storage

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

    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() {
     // 查询结果
    }
    Copy after login

    (2) Insert data

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

    (3) Update data

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

    ( 4) Delete data

    stmt, err := db.Prepare("DELETE FROM table_name WHERE col1 = ?")
    _, err = stmt.Exec(val)
    Copy after login
  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
     }
    }
    Copy after login
  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 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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

PHP's big data structure processing skills

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

How to optimize MySQL query performance in PHP?

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

How to use MySQL backup and restore in PHP?

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into a MySQL table using PHP?

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

How to use MySQL stored procedures in PHP?

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

How to create a MySQL table using PHP?

The difference between performance testing and unit testing in Go language The difference between performance testing and unit testing in Go language May 08, 2024 pm 03:09 PM

The difference between performance testing and unit testing in Go language

See all articles