doulierong0334 2018-07-19 06:39 采纳率: 100%
浏览 63

如何将数据从CSV导入MySQL

I have CSV x gb and want to insert into mysql, I would use Go for this, but I am not hitting the right way to do it, has anyone done that?

my proect: https://github.com/DevJoseWeb/AMCOM/tree/master/amcom-systems-go

  • 写回答

1条回答 默认 最新

  • duanjianlu0506 2018-07-19 07:00
    关注

    Regardless of the language, there's two basic approaches. First is to read and parse the CSV file yourself and insert one row at a time. This is inefficient.

    The other is to use MySQL's load data local infile to load a CSV file into a table letting MySQL do all the work. The local part means you'll be sending MySQL the CSV file.

    Unlike other SQL statements, this requires special client support to read and send the CSV file. Fortunately the go-sql-driver you're using has this support and notes a few caveats.

    Files must be whitelisted by registering them with mysql.RegisterLocalFile(filepath) (recommended) or the Whitelist check must be deactivated by using the DSN parameter allowAllFiles=true (Might be insecure!).

    To use a io.Reader a handler function must be registered with mysql.RegisterReaderHandler(name, handler) which returns a io.Reader or io.ReadCloser. The Reader is available with the filepath Reader:: then. Choose different names for different handlers and DeregisterReaderHandler when you don't need it anymore.

    See the godoc of Go-MySQL-Driver for details.

    Go-MySQL-Driver has examples. With RegisterLocalFile...

    filePath := "/home/gopher/data.csv"
    mysql.RegisterLocalFile(filePath)
    err := db.Exec("LOAD DATA LOCAL INFILE '" + filePath + "' INTO TABLE foo")
    if err != nil {
    ...
    

    And with RegisterReaderHandler.

    mysql.RegisterReaderHandler("data", func() io.Reader {
        var csvReader io.Reader // Some Reader that returns CSV data
        ... // Open Reader here
        return csvReader
    })
    err := db.Exec("LOAD DATA LOCAL INFILE 'Reader::data' INTO TABLE foo")
    if err != nil {
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题