如何避免在获取行数时使用下一个方法

时间:2019-03-10 19:44:47

标签: sql go

在php中,我可以打印出postid与下面的代码匹配的行数,而无需在while循环中传递结果。

$status_query = "SELECT count(*) as postCount FROM postData WHERE postid=1";
$status_result = mysqli_query($con,$status_query);
$status_row = mysqli_fetch_array($status_result);
$postCount = $status_row['postCount'];
echo $postCount;

现在,将相同行数的代码重新写入 golang 。我利用这里找到的Stackoverflow解决方案。 source link

有了上面的Stackoverflow解决方案链接,下面的golang代码可以很好地工作,因为我可以获得行数。

rows1, err := db.Query("SELECT COUNT(*) as postCount FROM postData WHERE postid=1")
if err != nil {
    log.Fatal(err)
}
defer rows1.Close()
var  postCount int

for rows1.Next() {   
    if err := rows1.Scan(& postCount); err != nil {
        log.Fatal(err)
    }
}

fmt.Printf("Number of rows are %s\n",  postCount)

这是我要修改的内容:

上面的代码在其中传递了行计数结果

for rows1. Next(){
// result here.
}

M y问题是:

由于我要根据postid检索行数,因此如何避免使用此for rows.next()函数,而直接获得我的结果。 在上面的php代码中,我可以直接获得结果,而无需在while循环中传递它。

golang 中,我想到的是下面的代码

rows1, err := db.Query("SELECT COUNT(*) as postCount FROM postData WHERE postid=1")
if err != nil {
    log.Fatal(err)
}
defer rows1.Close()
var status_row = rows1.Next() 

var postCount =rows1.Scan(& postCount)
fmt.Printf("Number of rows are %s\n",  postCount)

是否有人有更好的方法来使该行数直接显示而无需在rows1.Next()方法中传递结果

这是我在上面的编码插图中寻求修改之前的总体工作代码。

package main

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

import "net/http"
import "fmt"
import "log"

var db *sql.DB
var err error


func getRecordPage1(res http.ResponseWriter, req *http.Request) {

    if req.Method != "POST" {
        http.ServeFile(res, req, "getjsonRecord.html")
        return
    }

//The commented section below is the code I want to modify to avoid use of for rows.next function....
/*
rows1, err := db.Query("SELECT COUNT(*) as postCount FROM like_unlike WHERE postid=1")
if err != nil {
    log.Fatal(err)
}
defer rows1.Close()
var  postCount int

for rows1.Next() {   
    if err := rows1.Scan(& postCount); err != nil {
        log.Fatal(err)
    }
}

fmt.Printf("Number of rows are %s\n",  postCount)

}
*/


func homePage(res http.ResponseWriter, req *http.Request) {
    http.ServeFile(res, req, "index.html")
}

func main() {
    db, err = sql.Open("mysql", "root:@/golang44")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

    http.HandleFunc("/getjsonRecord", getRecordPage1)
    http.HandleFunc("/", homePage)
        fmt.Println("Listening on 127.0.0.1:8088")
    http.ListenAndServe(":8088", nil)
}

1 个答案:

答案 0 :(得分:3)

通常,如果您知道要排一行,请使用DB.QueryRow 它允许您链接查询并一起扫描,因此您的示例如下所示:

var  postCount int
err := db.QueryRow("SELECT COUNT(*) as postCount FROM postData WHERE postid=1").Scan(&postCount)
if err != nil {
    log.Fatal(err)
}