我正在從我的GO代碼中的postgreSQL
數據庫讀取數據,該工作流程一直順利進行,直到我嘗試使用包含字符%
的字符串類型的scan
列值。由此產生的掃描字符串將包含%!(MISSING)
而不是%。掃描包含%字符的數據庫查詢結果
例如,字符串值this is a % test
在掃描後變成this is a %!t(MISSING)est
。
我使用常規的lib/pq驅動程序去使用database.Query(...).Scan(...)
方法。
編輯:爲了明確我在做什麼以及我如何做。
我有一個接受的HTTP GET請求的功能:
func GetItems(w http.ResponseWriter, r *http.Request) {
// Setting header content type to json
w.Header().Set("Content-Type", "application/json")
// Calling another function that gets the items from postgres
// and returns them as []structs
items := pg.SelectItems(Database)
// Marshall the []struct into a json byte array
jsonItems, err := json.Marshal(items)
// return the formatted response
// I think that's where the problem is happening
w.WriteHeader(200)
fmt.Fprintf(w, string(response))
}
...和做查詢和掃描結果到GO結構的函數:
func SelectItems (database *sql.DB) []Items {
var result []Items
queryStatement := `SELECT item_id,item_value FROM items`
// Execute the DB Query
rows, err := database.Query(queryStatement)
// Loop over rows
for rows.Next() {
item := new(Item)
// Scan values into item's fields
err = rows.Scan(&item.ItemID, &item.ItemValue)
if err != nil {
// append the item to the array to be returned
result = append(result, item)
}
}
return result
}
...其中物品被定義爲這樣:
type Item struct {
ItemID string `json:"item_id"`
ItemValue string `json:"item_value"`
}
注:我知道最好的做法是始終處理所有錯誤,並確保在DB查詢後調用defer rows.Close()
..並且我在生產代碼中執行操作,但爲了清晰和易讀,我忽略了這些錯誤。
要提高你的問題,請添加一些代碼的實際行代表的問題。我個人很難想象失蹤的細節。 – miltonb
@miltonb你說得對。我在問題中加入了一些真正的代碼,使其更清晰。請注意,要測試該代碼,您需要運行一個sql db。在代碼中,'Database'對象是該數據庫的連接。 – Frax