The go language uses the Gin framework to link the database

The go language uses the Gin framework to link the database

Introduction

This article explains how to use the go language to link the database

Here are some steps to link the database with the Gin framework:

Assuming that the database you choose is MySQL, you first need to install the corresponding MySQL database in the system and create a database named "testdb".

  1. Install go-sql-driverthe driver. Type the following command in the command-line terminal:
go get github.com/go-sql-driver/mysql

After entering the download, you can see that there are related packages in go.sum
insert image description here

  1. Import the required packages. At the top of the code file, import the required packages with the following statement:
import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)
  1. Create a database connection pool object. In the main function or a custom function, connect to the MySQL database and create a new database connection pool.
func connectToDatabase() (*sql.DB, error) {
    
    
    // Set up the database source string.
    dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", username, password, host, port, dbname)

    // Create a database handle and open a connection pool.
    db, err := sql.Open("mysql", dataSourceName)
    if err != nil {
    
    
        return nil, err
    }

    // Check if our connection is alive.
    err = db.Ping()
    if err != nil {
    
    
        return nil, err
    }

    return db, nil
}
  1. Create a new connection in the router function (or any other function that needs to link to the database) and get the connection from the connection pool. Use the connectToDatabase function from the above steps, calling it when needed to get a connection to the MySQL database. Here is a simple example:
func main() {
    
    
    // Connect to the database.
    db, err := connectToDatabase()
    if err != nil {
    
    
        log.Fatal(err)
    }

    // Close the database connection pool after the main function returns.
    defer db.Close()

    // Create a new Gin router instance.
    r := gin.Default()

    // ...

    // Serve HTTP requests using the Gin router.
    r.Run(":8080")
}

create database

code demo database

-- 创建 testdb 数据库
CREATE DATABASE testdb;

-- 使用 testdb 数据库空间
USE testdb;

-- 创建 users 表并插入2条数据
CREATE TABLE users (
  id INT(11) NOT NULL AUTO_INCREMENT,
  username VARCHAR(100) NOT NULL,
  email VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO users (username, email) VALUES ('user1', '[email protected]');
INSERT INTO users (username, email) VALUES ('user2', '[email protected]');

This MySQL database contains a named testdbdatabase and a named userstable. usersThe table includes three fields: id, usernameand email, which are idthe primary key and auto-increment.

You can use the MySQL client to connect to the database (the default port is 3306), or use the following command to view the data in the table through the terminal command line:

USE testdb;
SELECT * FROM users;

The output should look like this:

+----+----------+------------------+
| id | username | email            |
+----+----------+------------------+
|  1 | user1    | [email protected] |
|  2 | user2    | [email protected] |
+----+----------+------------------+

full code

package main

import (
	"database/sql" // 数据库操作相关的包
	"fmt"
	"log" // 日志处理包

	"github.com/gin-gonic/gin" // Gin框架
	_ "github.com/go-sql-driver/mysql" // 加载MySQL驱动
)

const (
	username = "yourname"
	password = "yourpassword"
	host     = "localhost"
	port     = 3306
	dbname   = "testdb"
)

type user struct {
    
    
	ID       int    `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
}

// 连接数据库的函数。返回一个 *sql.DB 对象以及一个 error 对象 (如果连接不成功)。
func connectToDatabase() (*sql.DB, error) {
    
    
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", username, password, host, port, dbname)
	db, err := sql.Open("mysql", dataSourceName) // 打开名为 MySQL 的SQL数据库
	if err != nil {
    
    
		return nil, err
	}
	err = db.Ping() // 检查连接是否建立,以确保连接存活
	if err != nil {
    
    
		return nil, err
	}
	return db, nil
}

func main() {
    
    
	db, err := connectToDatabase() // 与 MySQL 数据库建立连接
	if err != nil {
    
    
		log.Fatal(err)
	}
	defer db.Close() // 延迟执行,确保在 main 函数退出时关闭数据库连接
	r := gin.Default() // 创建一个Gin路由器实例
	r.GET("/users/:id", func(c *gin.Context) {
    
     // 定义一个路由处理函数,用于从数据库中检索用户信息
		var (
			user   user  // 用户结构体,用于存储结果查询的记录
			result gin.H // Gin框架使用的Map集合类型,用于将结果渲染为 JSON 格式并发送给客户端
		)
		id := c.Param("id") // 获取参数id
		row := db.QueryRow("SELECT id, username, email FROM users WHERE id = ?", id) // 执行 SQL 查询,并返回*sql.Row对象,其中包含结果集的单行记录
		err = row.Scan(&user.ID, &user.Username, &user.Email) // 将行数据扫描到user 结构体内,分别对应结果集中的前3列(id,username,email)
		if err != nil {
    
    
			result = gin.H{
    
    
				"message": "User not found", // 如果错误则返回 error 消息
			}
		} else {
    
    
			result = gin.H{
    
    
				"data": user, //返回查询结果
			}
		}
		c.JSON(200, result) // 渲染result Map集合成JSON格式,并发送响应消息给客户端
	})
	r.Run(":8080") // 启动服务器并在本地机器上监听端口号为8080的请求
}

run code

insert image description here
Test success
insert image description here

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/130762946