golang Couchbase n1ql查询传递params到?

时间:2016-01-11 05:49:29

标签: go couchbase

我正在尝试找到一种将参数传递给查询的方法,但不太确定如何。 web site上的API看起来有点过时了吗?

myQuery := gocb.NewN1qlQuery("SELECT * FROM default")
rows, err := myBucket.ExecuteN1qlQuery(myQuery)
if err != nil {
    fmt.Printf("N1QL query error: %s\n", err)
}
var row interface{}
for rows.Next(&row) {
    fmt.Printf("Row: %+v\n", row)
}
if err := rows.Close(); err != nil {
    fmt.Printf("N1QL query error: %s\n", err)
}

因为实际上ExecuteN1qlQuery需要两个参数:

func (b *Bucket) ExecuteN1qlQuery(q *N1qlQuery, params interface{}) (ViewResults, error)

我不确定如何使用它...就像我想用占位符创建查询,并通过params将值传递给ExecuteN1qlQuery。与SQL一样(prepare - > execute)。例如:

    myQuery := gocb.NewN1qlQuery("SELECT * FROM default where a=? and b=?")
    rows, err := myBucket.ExecuteN1qlQuery(myQuery,[]string{"b","c"})
    if err != nil {
        fmt.Printf("N1QL query error: %s\n", err)
    }
    var row interface{}
    for rows.Next(&row) {
        fmt.Printf("Row: %+v\n", row)
    }
    if err := rows.Close(); err != nil {
        fmt.Printf("N1QL query error: %s\n", err)
    }

2 个答案:

答案 0 :(得分:3)

您发布的有关如何执行此操作的示例来自我们的开发人员指南repo on github:

https://github.com/couchbaselabs/devguide-examples/blob/master/go/query-placeholders.go

基本上,你使用$引用一个接口和一个以1开头的相应位置参数。

对于您的示例,它看起来像:

// Setup a new query with a placeholder
myQuery := gocb.NewN1qlQuery("SELECT * FROM default where a=$1 and b=$2")

// Setup an array for parameters
var myParams []interface{}
myParams = append(myParams,"foo")
myParams = append(myParams,"bar")

// Execute Query
rows, err := bucket.ExecuteN1qlQuery(myQuery, myParams)
if err != nil {
    fmt.Println("ERROR EXECUTING N1QL QUERY:", err)
}

// Iterate through rows and print output
var row interface{}
for rows.Next(&row) {
    fmt.Printf("Results: %+v\n", row)
}

答案 1 :(得分:0)

只需found example

        myQuery := gocb.NewN1qlQuery("SELECT airportname, city, country FROM `travel-sample` " +
        "WHERE type='airport' AND city=$1 ")

    // Setup an array for parameters
    var myParams []interface{}
    myParams = append(myParams, "Reno")

    // Execute Query
    rows, err := bucket.ExecuteN1qlQuery(myQuery, myParams)