Golang如何使用sql查询行检查错误

时间:2017-08-02 22:10:06

标签: go

我正在使用postgres数据库,并以字符串形式从数据库返回Json响应,该字符串用于API。我的问题是我不知道如何使用QueryRow方法检查错误。这是我的代码,它正常工作。这只是显示了Json的回应。但是我有一个自定义函数,如果代码有错误我想使用它,QueryRow不让我检查错误任何建议?

 var result string
 db.QueryRowContext(ctx,"select json_build_object('Profile', array_to_json(array_agg(t))) from" +
                    " (select p.id,p.fullname,z.thirtylatmin as latmin,z.thirtylatmax as latmax,z.thirtylonmin as lonmin," +
                          "z.thirtylonmax as lonmax,p.latitudes,p.longitudes,p.location as location" +
                    ",p.picture,p.is_gold from profiles p join zips z on (z.city='Boston' " +
                 "and z.state='MA') where email=$1) t;",email).Scan(&result)

io.writestring(w, result)

如果我将上面的代码改为this,那么它可以处理错误消息但是如何在String中返回

SqlStatement,err := db.QueryContext(ctx,"select json_build_object('Profile', array_to_json(array_agg(t))) from" +
                " (select p.id,p.fullname,z.thirtylatmin as latmin,z.thirtylatmax as latmax,z.thirtylonmin as lonmin," +
                      "z.thirtylonmax as lonmax,p.latitudes,p.longitudes,p.location as location" +
                ",p.picture,p.is_gold from profiles p join zips z on (z.city='Boston' " +
             "and z.state='MA') where email=$1) t;",email)

            if err != nil {
                log_errors("sql statement error",err.Error(),w)
            }
            io.WriteString(w, "How can I get SqlStatement as 1 whole String ??")

上面的语句让我记录任何错误并将其插入数据库,现在如何让SqlStatement返回1整个字符串? SQL语句现在完美地返回我只需要以String格式将其导入io.WriteString

1 个答案:

答案 0 :(得分:1)

您应该只检查Row.Scan方法的返回值,如下所示:

row := db.QueryRow(
    `SELECT 
        json_build_object('Profile', array_to_json(array_agg(t))) 
    FROM
        (
            SELECT 
                p.id,
                p.fullname,
                z.thirtylatmin as latmin,
                z.thirtylatmax as latmax,
                z.thirtylonmin as lonmin,
                z.thirtylonmax as lonmax,
                p.latitudes,
                p.longitudes,
                p.location as location,
                p.picture,
                p.is_gold 
            FROM 
                profiles p 
            JOIN zips z on (z.city='Boston'AND z.state='MA') 
            WHERE 
                email=$1
        ) t`,
    email,
)

var result string
if err := Scan(&result); err != nil {
    log.Fatal(err)
}

fmt.Fprint(w, result)