Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8484e14
commit 84c454b
Showing
2 changed files
with
63 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
package database | ||
|
||
import ( | ||
"database/sql" | ||
"time" | ||
|
||
"github.com/go-sql-driver/mysql" | ||
|
||
"goblog/pkg/logger" | ||
) | ||
|
||
// DB 数据库对象 | ||
var DB *sql.DB | ||
|
||
// Initialize 初始化数据库 | ||
func Initialize() { | ||
initDB() | ||
createTables() | ||
} | ||
|
||
func initDB() { | ||
|
||
var err error | ||
|
||
// 设置数据库连接信息 | ||
config := mysql.Config{ | ||
User: "root", | ||
Passwd: "secret", | ||
Addr: "127.0.0.1:3306", | ||
Net: "tcp", | ||
DBName: "goblog", | ||
AllowNativePasswords: true, | ||
} | ||
|
||
// 准备数据库连接池 | ||
DB, err = sql.Open("mysql", config.FormatDSN()) | ||
logger.LogError(err) | ||
|
||
// 设置最大连接数 | ||
DB.SetMaxOpenConns(100) | ||
// 设置最大空闲连接数 | ||
DB.SetMaxIdleConns(25) | ||
// 设置每个链接的过期时间 | ||
DB.SetConnMaxLifetime(5 * time.Minute) | ||
|
||
// 尝试连接,失败会报错 | ||
err = DB.Ping() | ||
logger.LogError(err) | ||
} | ||
|
||
func createTables() { | ||
createArticlesSQL := `CREATE TABLE IF NOT EXISTS articles( | ||
id bigint(20) PRIMARY KEY AUTO_INCREMENT NOT NULL, | ||
title varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, | ||
body longtext COLLATE utf8mb4_unicode_ci | ||
); ` | ||
|
||
_, err := DB.Exec(createArticlesSQL) | ||
logger.LogError(err) | ||
} |