普通网友 2018-10-02 08:14
浏览 284
已采纳

如何使用golang导入csv并保存在MSSQL数据库中?

This is my code. Currently, I just read the contents of the CSV file. I need to migrate this CSV file to MSSQL using Go Language Application

package main

import (
    "encoding/csv"
    "log"
    "os"
)

func main() {
    rows := readOrders("Ec2Instances.csv")
}

func readOrders(name string) [][]string {
    f, err := os.Open(name)
    if err != nil {
        log.Fatalf("Cannot open '%s': %s
", name, err.Error())
    }
    defer f.Close()
    r := csv.NewReader(f)
    r.Comma = ';'
    rows, err := r.ReadAll()
    if err != nil {
        log.Fatalln("Cannot read CSV data:", err.Error())
    }
    return rows
}

I want the CSV file to be written specifically into the "MSSQL Database". I have installed MSSQL and SSMS Softwares. How do I access these and write data into it?

  • 写回答

1条回答 默认 最新

  • douchangmian0305 2018-10-02 23:19
    关注

    It looks like you're half way there!

    Your sample code looks like it will read CSV data from a named file. The next step would be to connect to the MSSQL database instance and insert the rows from the CSV data.

    To do so, you'll need to find a golang driver for that database (denisenkom/go-mssqldb looks worth trying, there's even a simple example) and follow the patterns established by the go database/sql package (especially the package examples).

    A working solution might look something like this (not working but demonstrative):

    import (
      "database/sql"
      _ "github.com/denisenkom/go-mssqldb"
      // ...
    )
    
    func main() {
      rows := readOrders("Ec2Instances.csv")
      insertRowsToDatabase(rows)
    }
    
    func insertRowsToDatabase(rows [][]string) {
      // Connect to the database.
      connString := "server=myserver;user id=123;password=secret;port=234"
      db, err := sql.Open("mssql", connString)
      if err != nil {
        log.Fatal("Open connection failed:", err.Error())
      }
      defer db.Close()
    
      // Insert the rows, omitting the first header row from the CSV.
      stmt, err := db.Prepare("INSERT INTO Ec2Instances(id, name) VALUES(?, ?)")
      if err != nil {
        log.Fatal(err)
      }
      for _, row := range rows[1:] {
        _, err := stmt.Exec(row[0], row[1])
        if err != nil {
          log.Fatal(err)
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用