duanjun7801 2017-04-16 17:21
浏览 382
已采纳

如何使用Golang从文件直接执行MSSQL脚本

I have been looking around for the answer to the question above with no luck. Excuse me if it is a duplicate. So basically I am trying to execute a sql script directly from file but I keep on getting the " Incorrect syntax near ''. " error

func AnotherDatabase() (sql.Result, error) {
     rc, err := os.Open("./myscript.sql")
     if err != nil {
        return nil,err
     }
     buf := new(bytes.Buffer)
     buf.ReadFrom(rc)
     contents := buf.String()

     db, err := sql.Open("mssql", "mydatabase")
     if err != nil {
       return nil,err
     }
     defer db.Close()

     res, err := db.Exec(contents)
     if err != nil {
       return nil,err
     }
    return res,nil
}
  • 写回答

1条回答 默认 最新

  • dongyi5425 2017-04-17 16:11
    关注

    I have realized the illegal character causing issues was probably an extended ASCII character so I used the below method to strip off unnecessary characters from the file contents :

    func stripCtlAndExtFromBytes(str string) string {
      b := make([]byte, len(str))
      var bl int
      for i := 0; i < len(str); i++ {
        c := str[i]
        if c >= 32 && c < 127 {
          b[bl] = c
          bl++
         }
     }
     return string(b[:bl])
    }
    

    as stated here https://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string#Go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺