普通网友 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)
        }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站