2014-07-12 83 views
0

我試圖通過這種方式獲取數據庫的值。但是當我進入/ 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中。

預先感謝您。

回答

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 }} 
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

+0

但我想數據庫的值。這是否真的像這樣的價值? – Coluh

+0

@devtreat更新 –

+0

我得到了相同的代碼,現在我得到了這個錯誤:pq:語法錯誤在或「或」附近。 – Coluh

相關問題