doudao9896
doudao9896
2016-06-29 20:30

Golang如何使SQL行成为字符串

已采纳

I am using Golang and Postgres, Postgres has an advance feature where it can return your queries in Json format. What I want to do is get that Json query results and return it but I am having trouble since it has to be a String in order to return it. This is my code

 package main

    import(
        "fmt"
        "database/sql"
        _ "github.com/lib/pq"

        "log"
    )

    func HelloServer(w http.ResponseWriter, req *http.Request) {

     db, err := sql.Open("postgres", "user=postgres password=password dbname=name sslmode=disable")

        if err != nil {
            log.Fatal(err)
        }

         defer db.Close()
        rows, err := db.Query("select To_Json(t) (SELECT * from cars)t")

    io.WriteString(w, "hello, world!
")
}


 func main() {
    http.HandleFunc("/hello", HelloServer)
    log.Fatal(http.ListenAndServe(":12345", nil))
}

The Rows element returns a Json array how can I turn that Rows element into a String ? For C# and Java I would just append the .ToString() method to it and it would make it a string . As you can see from the code above the io.WriteString takes a String as a second parameter so I want to make the Rows variable a String after it has the Json returned so that I can display it in the browser by passing it to the method. I want to replace the Hello World with the String Rows.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douhan4812 douhan4812 5年前

    Rows is a sql.Rows type. In order to use the data returned by your database query you will have to iterated over the "rows".

    An example from the docs

    age := 27
    rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
    if err != nil {
            log.Fatal(err)
    }
    defer rows.Close()
    for rows.Next() {
            var name string
            if err := rows.Scan(&name); err != nil {
                    log.Fatal(err)
            }
            fmt.Printf("%s is %d
    ", name, age)
    }
    if err := rows.Err(); err != nil {
            log.Fatal(err)
    }
    

    You should instead use QueryRow because you are expecting the database to return one result. In either case once you have used "Scan" to put the data into your own variable then you can either parse the JSON or print it out.

    点赞 评论 复制链接分享

为你推荐