package main
import (
"database/sql"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
var dbHost = "127.0.0.1"
var dbUser = "root"
var dbPwd = "123456"
var dbPort = "3306"
var dbName = "test"
var sqlFile = "test.sql"
var accessToken = "fiegut3johg383tio"
// 清空表
func dropTable() {
sqlStr := `SELECT table_name tableName,TABLE_COMMENT tableDesc
FROM INFORMATION_SCHEMA.TABLES
WHERE UPPER(table_type)='BASE TABLE'
AND LOWER(table_schema) = ?
ORDER BY table_name asc`
var result = make(map[string]string)
rows, err := db.Query(sqlStr, dbName)
for rows.Next() {
var tableName, tableDesc string
err = rows.Scan(&tableName, &tableDesc)
checkErr(err)
if len(tableDesc) == 0 {
tableDesc = tableName
}
result[tableName] = tableDesc
}
for i := range result {
sqlStr := "DROP TABLE " + result[i]
fmt.Println(sqlStr)
db.Query(sqlStr)
}
importTable()
}
// 导入表
func importTable() {
f, err := os.Open(sqlFile)
defer f.Close()
if err != nil {
fmt.Println("打开文件失败", err)
}
data, err := ioutil.ReadFile(sqlFile)
if err != nil {
fmt.Println("文件读取失败", err)
return
}
sqlStr := string(data)
val := strings.Split(sqlStr, ";\n")
if len(val) == 0 {
return
}
for i := range val {
if len(val[i]) == 0 {
continue
}
db.Exec(val[i])
}
}
// 打印数据
func p(data interface{}) {
fmt.Println("-------------------------")
fmt.Println(data)
fmt.Println("-------------------------")
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
//连接MYSQL test
var err error
db, err = sql.Open("mysql", ""+dbUser+":"+dbPwd+"@tcp("+dbHost+":"+dbPort+")/"+dbName+"?parseTime=true")
if err != nil {
log.Fatal(err.Error())
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal(err.Error())
}
//创建一个路由Handler
router := gin.Default()
router.GET("/token/:token", func(c *gin.Context) {
token := c.Param("token")
if token != accessToken {
c.String(http.StatusOK, "token err")
return
}
dropTable()
c.String(http.StatusOK, "token %s ", token)
})
router.Run(":8080")
}
有疑问加站长微信联系(非本文作者)