doudao9896 2016-06-29 20:30
浏览 325
已采纳

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 2016-06-29 20:36
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?