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
-
:ensure
InitDB
The 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=Local
Such 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 callInitDB
Initialize the database connection and useGetDB
Get 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 yoursUser
The 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 provide
InitDB
andGetDB
Functions 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!