Files
nl-game-api/tools/dbinit/main.go
2026-08-14 13:17:03 +08:00

46 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 数据库初始化工具:读取 sql/init.sql 并整体执行(建库建表+种子数据)
// 使用方式:在 backend 目录下执行 go run ./tools/dbinit
package main
import (
"database/sql"
"fmt"
"os"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// 读取初始化 SQL 脚本(相对 backend 目录的上级 sql 目录)
content, err := os.ReadFile("../sql/init.sql")
if err != nil {
fmt.Println("读取 sql/init.sql 失败:", err)
os.Exit(1)
}
// 连接本地 MySQL不指定库名因为脚本内部会自行建库
// multiStatements=true 允许一次执行整个脚本
dsn := "root:root@tcp(127.0.0.1:3306)/?charset=utf8mb4&multiStatements=true"
db, err := sql.Open("mysql", dsn)
if err != nil {
fmt.Println("连接 MySQL 失败:", err)
os.Exit(1)
}
defer db.Close()
if err := db.Ping(); err != nil {
fmt.Println("MySQL 无法连通(请确认 3306 端口、账号 root/root:", err)
os.Exit(1)
}
// 整体执行初始化脚本
if _, err := db.Exec(string(content)); err != nil {
fmt.Println("执行初始化脚本失败:", err)
os.Exit(1)
}
// 简单校验:统计游戏数量确认种子数据写入成功
var gameCount int
if err := db.QueryRow("SELECT COUNT(*) FROM xiaoyouxi.games").Scan(&gameCount); err != nil {
fmt.Println("校验失败:", err)
os.Exit(1)
}
fmt.Printf("数据库初始化成功games 表共 %d 款游戏\n", gameCount)
}