golang 数据库连接池
【摘要】 简介本文介绍如何使用gorm 2 连接池的使用代码例子,该连接池支持Mysql、postgres、sqlite三种数据库。安装依赖go get gorm.io/gormgo get gorm.io/driver/mysqlgo get gorm.io/driver/postgresgo get gorm.io/driver/sqlite数据库配置文件配置文件{ "database": { ...
简介
本文介绍如何使用gorm 2 连接池的使用代码例子,该连接池支持Mysql、postgres、sqlite三种数据库。
安装依赖
go get gorm.io/gorm go get gorm.io/driver/mysql go get gorm.io/driver/postgres go get gorm.io/driver/sqlite
数据库配置文件
配置文件
{ "database": { "name": "db1", "password": "123456", "user": "root", "type": "mysql", "host": "127.0.0.1", "port": "3306", "table_prefix": "" } }
读取配置文件代码
package configimport ( "encoding/json" "os")// Config 配置对象type Config struct { Database *Database `json:"database"`}// GlobalConfigSetting 配置实例var GlobalConfigSetting = &Config{}// Setup 配置func Setup() { filePtr, err := os.Open("config/config.json") //config的文件目录 if err != nil { return } defer filePtr.Close() // 创建json解码器 decoder := json.NewDecoder(filePtr) err = decoder.Decode(GlobalConfigSetting) DatabaseSetting = GlobalConfigSetting.Database }// Database 数据库配置对象type Database struct { Type string `json:"type"` User string `json:"user"` Password string `json:"password"` Host string `json:"host"` Port string `json:"port"` Name string `json:"name"` TablePrefix string `json:"table_prefix"`}// DatabaseSetting 数据库配置对象 实例var DatabaseSetting = &Database{}
连接池代码
package daoimport ( "fmt" "log" "report/src/config" "time" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm")// db连接var db *gorm.DB// Setup 初始化连接func Setup() { // db = newConnection() var dbURI string var dialector gorm.Dialector if config.DatabaseSetting.Type == "mysql" { dbURI = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=true", config.DatabaseSetting.User, config.DatabaseSetting.Password, config.DatabaseSetting.Host, config.DatabaseSetting.Port, config.DatabaseSetting.Name) dialector = mysql.New(mysql.Config{ DSN: dbURI, // data source name DefaultStringSize: 256, // default size for string fields DisableDatetimePrecision: true, // disable datetime precision, which not supported before MySQL 5.6 DontSupportRenameIndex: true, // drop & create when rename index, rename index not supported before MySQL 5.7, MariaDB DontSupportRenameColumn: true, // `change` when rename column, rename column not supported before MySQL 8, MariaDB SkipInitializeWithVersion: false, // auto configure based on currently MySQL version }) } else if config.DatabaseSetting.Type == "postgres" { dbURI = fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", config.DatabaseSetting.Host, config.DatabaseSetting.Port, config.DatabaseSetting.User, config.DatabaseSetting.Name, config.DatabaseSetting.Password) dialector = postgres.New(postgres.Config{ DSN: "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai", PreferSimpleProtocol: true, // disables implicit prepared statement usage }) } else { // sqlite3 dbURI = fmt.Sprintf("test.db") dialector = sqlite.Open("test.db") } conn, err := gorm.Open(dialector, &gorm.Config{}) if err != nil { log.Print(err.Error()) } sqlDB, err := conn.DB() if err != nil { fmt.Error("connect db server failed.") } sqlDB.SetMaxIdleConns(10) // SetMaxIdleConns sets the maximum number of connections in the idle connection pool. sqlDB.SetMaxOpenConns(100) // SetMaxOpenConns sets the maximum number of open connections to the database. sqlDB.SetConnMaxLifetime(time.Second * 600) // SetConnMaxLifetime sets the maximum amount of time a connection may be reused. db = conn }// GetDB 开放给外部获得db连接func GetDB() *gorm.DB { sqlDB, err := db.DB() if err != nil { fmt.Errorf("connect db server failed.") Setup() } if err := sqlDB.Ping(); err != nil { sqlDB.Close() Setup() } return db }
使用示例
package domainimport ( "report/src/dao" "gorm.io/gorm")// Product 产品type Product struct { gorm.Model Code string Price uint}// Test 测试func (Product) Test() { db := dao.GetDB() // 自动迁移模式 db.AutoMigrate(&Product{}) // 创建 db.Create(&Product{Code: "L1212", Price: 1000}) }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)