SoFunction
Updated on 2025-04-07

Simple example of GoZero implementing database MySQL singleton pattern connection

1. Define the singleton structure of the database connection

First, you need to define a structure for the database connection and ensure that there is only one connection when initializing.

package database

import (
	"fmt"
	"log"
	"sync"

	"/driver/mysql"
	"/gorm"
)

var (
	db   *
	once 
)

// InitDB initializes the database connectionfunc InitDB(dsn string) {
	(func() {
		var err error
		db, err = ((dsn), &{})
		if err != nil {
			("failed to connect database: %v", err)
		}
		("Database connected successfully")
	})
}

// GetDB gets the database connectionfunc GetDB() * {
	if db == nil {
		("Database is not initialized")
	}
	return db
}

2. Description

  • :ensureInitDBThe function will only be executed once, and even multiple calls will initialize the database connection once.
  • dsn: You need to pass in the DSN (Data Source Name) of the database connection, usually similarusername:password@tcp(host:port)/dbname?charset=utf8mb4&parseTime=True&loc=LocalSuch a format.
  • GetDB(): Returns the connection to the database. If the database is not initialized, an error will be triggered.

3. How to use

In your business code, just callInitDBInitialize the database connection and useGetDBGet the database connection for operation.

package main

import (
	"log"
	"myapp/database"
)

func main() {
	// Initialize the database connection	("root:password@tcp(localhost:3306)/mydb?charset=utf8mb4&parseTime=True&loc=Local")
	
	// Get the database connection	db := ()

	// Execute database operations, such as querying data	var user User
	if err := (&user).Error; err != nil {
		("Error querying user: %v", err)
	}

	// Output query results	("User: %+v", user)
}

4. Complete example

Assume yoursUserThe structure is defined as follows:

package main

type User struct {
	ID   uint   `gorm:"primaryKey"`
	Name string `gorm:"size:255"`
}

In this way, you can ensure that the database connection will be created only once during the entire life of the application, thus implementing the singleton pattern of the database connection.

Summarize

Use this methodTo ensure that the database connection has only one instance in the application and provideInitDBandGetDBFunctions to initialize and get database connections. This approach is very suitable for projects in the GoZero framework and can effectively reduce unnecessary database connection creation.

This is the article about this simple example of GoZero implementing database MySQL singleton pattern connection. For more information about GoZero MySQL singleton pattern connection, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!