main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "strings"
  8. )
  9. func main(){
  10. // 获取当前路径
  11. path := GetCurrentDirectory()
  12. //if len(os.Args) < 2 {
  13. // fmt.Println("参数输入错误:例 : " )
  14. // return
  15. //}
  16. paraMap := make(map[string]string, 0)
  17. paraMap["-h"] = "localhost"
  18. paraMap["-port"] = "3306"
  19. paraMap["-u"] = "root"
  20. paraMap["-p"] = "root123456"
  21. paraMap["-path"] = path+"/1.sql"
  22. paraMap["-database"] = "test"
  23. for i := 1; i < len(os.Args); i++ {
  24. if len(os.Args) > i+1 {
  25. paraMap[strings.ToLower(os.Args[i])] = strings.Trim(strings.ToLower(os.Args[i+1]), " ")
  26. } else {
  27. paraMap[strings.ToLower(os.Args[i])] = ""
  28. }
  29. }
  30. out, err := Exec_Shell(paraMap)
  31. if err != nil{
  32. fmt.Println(string(out))
  33. fmt.Println(err.Error())
  34. }
  35. }
  36. func GetCurrentDirectory() string {
  37. //返回绝对路径 filepath.Dir(os.Args[0])去除最后一个元素的路径
  38. dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
  39. if err != nil {
  40. os.Exit(0)
  41. }
  42. //将\替换成/
  43. return strings.Replace(dir, "\\", "/", -1)
  44. }
  45. func Exec_Shell(paraMap map[string]string) (string, error) {
  46. command := fmt.Sprintf("mysql -P %s -h %s -u%s -p%s %s < %s",paraMap["-port"],paraMap["-h"],paraMap["-u"],paraMap["-p"],paraMap["-database"],paraMap["-path"])
  47. fmt.Println(command)
  48. cmd := exec.Command("/bin/sh", "-c", command)
  49. out, err := cmd.CombinedOutput()
  50. if err != nil{
  51. fmt.Println(string(out))
  52. fmt.Println(err.Error())
  53. }
  54. return string(out), err
  55. }