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

huangapple go评论135阅读模式
英文:

How to execute mssql script directly from file with Golang

问题

我一直在寻找上述问题的答案,但没有找到。如果这是一个重复的问题,请原谅。基本上,我正在尝试直接从文件中执行一个 SQL 脚本,但是我一直收到“Incorrect syntax near ''”的错误。

  1. func AnotherDatabase() (sql.Result, error) {
  2. rc, err := os.Open("./myscript.sql")
  3. if err != nil {
  4. return nil, err
  5. }
  6. buf := new(bytes.Buffer)
  7. buf.ReadFrom(rc)
  8. contents := buf.String()
  9. db, err := sql.Open("mssql", "mydatabase")
  10. if err != nil {
  11. return nil, err
  12. }
  13. defer db.Close()
  14. res, err := db.Exec(contents)
  15. if err != nil {
  16. return nil, err
  17. }
  18. return res, nil
  19. }

以上是要翻译的内容。

英文:

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

  1. func AnotherDatabase() (sql.Result, error) {
  2. rc, err := os.Open("./myscript.sql")
  3. if err != nil {
  4. return nil,err
  5. }
  6. buf := new(bytes.Buffer)
  7. buf.ReadFrom(rc)
  8. contents := buf.String()
  9. db, err := sql.Open("mssql", "mydatabase")
  10. if err != nil {
  11. return nil,err
  12. }
  13. defer db.Close()
  14. res, err := db.Exec(contents)
  15. if err != nil {
  16. return nil,err
  17. }
  18. return res,nil
  19. }

答案1

得分: 0

我已经意识到导致问题的非法字符可能是扩展ASCII字符,所以我使用了下面的方法从文件内容中去除不必要的字符:

  1. func stripCtlAndExtFromBytes(str string) string {
  2. b := make([]byte, len(str))
  3. var bl int
  4. for i := 0; i < len(str); i++ {
  5. c := str[i]
  6. if c >= 32 && c < 127 {
  7. b[bl] = c
  8. bl++
  9. }
  10. }
  11. return string(b[:bl])
  12. }

如此处所述:https://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string#Go

英文:

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 :

  1. func stripCtlAndExtFromBytes(str string) string {
  2. b := make([]byte, len(str))
  3. var bl int
  4. for i := 0; i &lt; len(str); i++ {
  5. c := str[i]
  6. if c &gt;= 32 &amp;&amp; c &lt; 127 {
  7. b[bl] = c
  8. bl++
  9. }
  10. }
  11. return string(b[:bl])
  12. }

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

huangapple
  • 本文由 发表于 2017年4月17日 01:21:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/43439929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定