importer.go 801 B

123456789101112131415161718192021222324252627282930
  1. package util
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "strconv"
  6. "github.com/go-sql-driver/mysql"
  7. )
  8. func MysqlImporter(conf *MySQLConfig, filePath, table, fields string) int64 {
  9. dsn := conf.Mysql_User + ":" + conf.Mysql_Password +
  10. "@tcp(" + conf.Mysql_Host + ":" + strconv.Itoa(conf.Mysql_Port) + ")/" +
  11. conf.Mysql_Name + "?charset=utf8&parseTime=True&allowAllFiles=true"
  12. db, err := sql.Open("mysql", dsn)
  13. if err != nil {
  14. return 0
  15. }
  16. defer db.Close()
  17. mysql.RegisterLocalFile(filePath)
  18. strSQL := fmt.Sprintf(`LOAD DATA LOCAL INFILE '%s' INTO TABLE %s
  19. CHARACTER SET UTF8 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (%s)`,
  20. filePath, table, fields)
  21. result, err_exec := db.Exec(strSQL)
  22. if err_exec != nil {
  23. return 0
  24. }
  25. rowsaffected, _ := result.RowsAffected()
  26. return rowsaffected
  27. }