去,没有参数$ 1

时间:2014-07-12 11:29:11

标签: sql postgresql templates go

我试图通过这种方式获取数据库的值。但是当我转到/ myapps方向时,编译器会给我一个错误。

结构:

type App struct{
    Title string
    Author string
    Description string
}

功能:

func myappsHandler(w http.ResponseWriter, r *http.Request){
    db, err := sql.Open("postgres"," user=postgres dbname=lesson4 host=localhost password=1234 sslmode=disable")
    if err != nil{
        log.Fatal(err)
    }
        rows, err := db.Query(`SELECT title, author, description FROM apps
                                 WHERE title ILIKE $1
                                 OR author ILIKE $1
                                 OR description ILIKE $1`)
            defer rows.Close()

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

            apps := []App{}
            for rows.Next(){
                b := App{}
                err := rows.Scan(&b.Title, &b.Author, &b.Description)

                if err != nil{
                log.Fatal(err)
            }
                apps = append(apps, b)
            }

            render(w, "myapps.html", map[string]interface{}{"apps" : apps})

        db.Close()
}

我在HTML中读到这样的内容:

{{ range .apps}}
  <tr>
    <td>{{ .Title }}</td>
    <td>{{ .Author }}</td>
    <td>{{ .Description }}</td>
    <td> <form action="/delete">
          <p class="navbar-form navbar-right"><button type="submit" class="btn btn-danger">Borrar</button> </p>
       </form></td>
  </tr>
{{ end  }}

错误是:没有参数$ 1.

提前谢谢。

2 个答案:

答案 0 :(得分:4)

您需要传递参数

title := '%the title%'
author := '%John%'
description := '%a book%'

rows, err := db.Query(`
    SELECT title, author, description
    FROM apps
    WHERE title ILIKE $1
          OR author ILIKE $2
          OR description ILIKE $3`
    , title, author, description
)

http://golang.org/pkg/database/sql/#DB.Query

使用%字符表示匹配任何内容

http://www.postgresql.org/docs/current/static/functions-matching.html#FUNCTIONS-LIKE

答案 1 :(得分:0)

我能够解决我的问题,谢谢你的回答和帮助:)。

我将发布工作代码:

结构:

type App struct{
    Title string
    Author string
    Description string
}

应用程序处理程序:

 db := SetupDB()

        rows, err := db.Query(`SELECT title, author, description FROM apps`)
            PanicIf(err)

            defer rows.Close()

            apps := []App{}
            for rows.Next(){
                b := App{}
                err := rows.Scan(&b.Title, &b.Author, &b.Description)
            PanicIf(err)

                apps = append(apps, b)
            }

            render(w, "myapps.html", map[string]interface{}{"apps" : apps})

        db.Close()

和html:

{{ range .apps}}
  <tr>
    <td>{{ .Title }}</td>
    <td>{{ .Author }}</td>
    <td>{{ .Description }}</td>
    <td> <form action="/delete">
          <p class="navbar-form navbar-right"><button type="submit" class="btn btn-danger">Borrar</button> </p>
       </form></td>
  </tr>
{{ end  }}