Using MySQL in Go: A Complete Guide

王林
Release: 2023-06-17 08:57:10
Original
5517 people have browsed it

With the continuous emergence of Internet applications, databases have become an indispensable component. As one of the most popular relational databases, MySQL has been widely used in development. In Go language, how to use MySQL for database development? This article will give readers a detailed introduction to the complete guide required to use MySQL in the Go language.

1. Install the MySQL driver: Go-MySQL-Driver

To use MySQL in Go language, you must install the MySQL driver. Currently, the Go language officially provides a sql package, but it does not provide a MySQL driver, so a third-party library needs to be used. Go-MySQL-Driver is the MySQL driver officially recommended by the Go language and is the best choice for using MySQL in the Go language. The installation is very simple, you can use the following code to install:

go get -u github.com/go-sql-driver/mysql
Copy after login

2. Connect to MySQL database

Before using MySQL, you need to connect to the MySQL database first. Connecting to a MySQL database requires using the database's connection string. The connection string includes user name, password, address, port number, database name and other information.

The code example for connecting to the MySQL database is as follows:

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

func openDB() (*sql.DB, error) {
  db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
  if err != nil {
    return nil, err
  }
  return db, nil
}
Copy after login

Code analysis:

Use the sql.Open() method to open the MySQL connection. The first parameter is the MySQL driver name. The second parameter is the connection string for the MySQL database. Among them, the connection string contains information related to the user name, password, address and port number, and the last one is the database name.

3. Create a data table

After connecting to MySQL, the next step is to create a data table. To operate the table, you need to use database objects. In the Go language, the database object is of the sql.DB type, through which database operations can be performed, including creating, modifying, and deleting data tables.

The code example of using golang to create a data table is as follows:

func create() error {
  db, err := openDB()
  if err != nil {
    return err
  }
  defer db.Close()
  _, err = db.Exec(`
    CREATE TABLE IF NOT EXISTS Users (
      id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
      name VARCHAR(50) NOT NULL, 
      age INT NOT NULL, 
      email VARCHAR(50) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  `)
  if err != nil {
    return err
  }
  return nil
}
Copy after login

Code analysis:

The code first connects to the MySQL database through the Open() method, and then executes the process of creating the table SQL command, MySQL command must write ().

4. Insert data

After creating the data table, the next step is to insert data into the table. Inserting data in Go language requires using the Exec() method of the database object.

The code example for inserting data is as follows:

func insert() error {
  db, err := openDB()
  if err != nil {
    return err
  }
  defer db.Close()
  _, err = db.Exec("INSERT INTO Users (name, age, email) VALUES (?, ?, ?)", "Tom", 23, "tom@example.com")
  if err != nil {
    return err
  }
  return nil
}
Copy after login

Code analysis:

When inserting data into the database, the first parameter of the Exec() method is the SQL command. Variable values ​​are used to pass parameters to SQL commands. Parameter names are represented by question marks (?).

5. Query data

Go language queries the database through the Query() function. The Query() function type is func Query(query string, args...interface{}). The first parameter is the SQL query statement, and the second parameter is the value of the parameter required in the SQL query statement. Separate parameters with commas.

The code example for querying data is as follows:

func query() error {
  db, err := openDB()
  if err != nil {
    return err
  }
  defer db.Close()
  rows, err := db.Query("SELECT id, name, age, email FROM Users")
  if err != nil {
    return err
  }
  defer rows.Close()

  for rows.Next() {
    var id, age int
    var name, email string
    if err := rows.Scan(&id, &name, &age, &email); err != nil {
      return err
    }
    fmt.Println(id, name, age, email)
  }
  return nil
}
Copy after login

Code analysis:

Use the Query() method to perform query operations, and use the Scan() method to read line by line Get data.

6. Modify data

To modify data in Go language, you need to use the Exec() method of the database object.

The sample code for modifying data is as follows:

func update() error {
  db, err := openDB()
  if err != nil {
    return err
  }
  defer db.Close()
  _, err = db.Exec("UPDATE Users SET age = ? WHERE name = ?", 25, "Tom")
  if err != nil {
    return err
  }
  return nil
}
Copy after login

Code analysis:

Use the Exec() method to perform modification operations.

7. Deleting data

To delete data in Go language, you need to use the Exec() method of the database object and execute the DELETE statement.

The sample code for deleting data is as follows:

func delete() error {
  db, err := openDB()
  if err != nil {
    return err
  }
  defer db.Close()
  _, err = db.Exec("DELETE FROM Users WHERE name = ?", "Tom")
  if err != nil {
    return err
  }
  return nil
}
Copy after login

Code analysis:

Use the Exec() method to perform the deletion operation.

8. Summary

The above is a complete guide to using MySQL in Go language. Through this article, we can see the best practices of combining Go language and MySQL database. Operating the MySQL database in Go language is very simple and intuitive, and the compatibility between Go language and MySQL is excellent. Finally, I hope this article can help you better understand and master the skills of using MySQL in Go language.

The above is the detailed content of Using MySQL in Go: A Complete Guide. For more information, please follow other related articles on the PHP Chinese website!

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