71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
|
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
"io/ioutil"
|
||
|
|
"log"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
_ "github.com/go-sql-driver/mysql"
|
||
|
|
)
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
// MySQL连接信息
|
||
|
|
username := "root"
|
||
|
|
password := "root"
|
||
|
|
hostname := "127.0.0.1"
|
||
|
|
port := "3306"
|
||
|
|
|
||
|
|
// 构建DSN (Data Source Name)
|
||
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", username, password, hostname, port)
|
||
|
|
|
||
|
|
// 连接到MySQL服务器
|
||
|
|
db, err := sql.Open("mysql", dsn)
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to open database connection: %v", err)
|
||
|
|
}
|
||
|
|
defer db.Close()
|
||
|
|
|
||
|
|
// 测试连接
|
||
|
|
if err := db.Ping(); err != nil {
|
||
|
|
log.Fatalf("Failed to ping database: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println("Connected to MySQL server successfully!")
|
||
|
|
|
||
|
|
// 读取SQL文件 (Assuming running from server root or adjusted path)
|
||
|
|
// If running from scripts/, path should be ../nl_blog.sql
|
||
|
|
sqlFile, err := ioutil.ReadFile("../nl_blog.sql")
|
||
|
|
if err != nil {
|
||
|
|
// Try current dir if run from root
|
||
|
|
sqlFile, err = ioutil.ReadFile("nl_blog.sql")
|
||
|
|
if err != nil {
|
||
|
|
log.Fatalf("Failed to read SQL file: %v", err)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 分割SQL语句
|
||
|
|
sqlStatements := strings.Split(string(sqlFile), ";")
|
||
|
|
|
||
|
|
// 执行每个SQL语句
|
||
|
|
for _, stmt := range sqlStatements {
|
||
|
|
// 跳过空语句
|
||
|
|
stmt = strings.TrimSpace(stmt)
|
||
|
|
if stmt == "" {
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
// 执行语句
|
||
|
|
_, err := db.Exec(stmt)
|
||
|
|
if err != nil {
|
||
|
|
log.Printf("Error executing statement: %v", err)
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Printf("Executed statement: %s\n", stmt)
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println("Database initialization completed!")
|
||
|
|
}
|