Created
July 15, 2024 18:36
-
-
Save BK1031/9660fb14bc2a202a34f49aab47aa4e6a to your computer and use it in GitHub Desktop.
singlestore-go-bookstore database connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package database | |
import ( | |
"bookstore/config" | |
"bookstore/model" | |
"fmt" | |
"log" | |
"gorm.io/driver/mysql" | |
"gorm.io/gorm" | |
) | |
var DB *gorm.DB | |
func InitializeDB() { | |
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=UTC", config.Database.Username, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.Database) | |
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) | |
if err != nil { | |
log.Fatalf("Failed to connect to database: %v", err) | |
} | |
log.Println("Connected to database") | |
db.AutoMigrate(&model.Book{}, &model.Order{}, &model.OrderItem{}) | |
DB = db | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment