我使用的是go 1.10.3,我尝试使用sqlx包获取一行并使用Get()将其输入到结构中,或者使用Select()获取多行并将其输入到切片中。
让我们从将一行放入一个结构开始。
我创建了以下结构:
type PsqlProduct struct {
Id int64 `db:"product_id"`
Name string `db:"product_name"`
Desc sql.NullString `db:"product_desc"`
YearManufacture sql.NullInt64 `db:"year_manufacture"`
Quantity sql.NullInt64 `db:"quantity"`
}对于查询:
QUERY_SELECT_PRODUCT = `select wd.product.id as product_id,
trans_p_name.text as product_name,
trans_p_desc.text as product_desc,
wd.product.year_manufacture, wd.product.quantity
from wd.product
join wd.text_translation as trans_p_name
on trans_p_name.text_id = wd.product.product_name_trans_id and trans_p_name.lang_id=1
left join wd.text_translation as trans_p_desc
on trans_p_desc.text_id = wd.product.product_desc_trans_id and trans_p_desc.lang_id=1
where wd.product.id = $1
`我创建了以下函数来通过id获取产品:
func PsqlGetProductById(productId int) *Product {
product := new(PsqlProduct)
err := Psqldb.Get(&product, QUERY_SELECT_PRODUCT,productId)
if err != nil {
log.Fatalf("error: %v",err)
return nil
} else {
newp := Product{
ID: uint(product.Id),
Name: product.Name,
}
if product.Quantity.Valid {
newp.Quantity = uint16(product.Quantity.Int64)
}
if product.YearManufacture.Valid {
newp.YearManufacture = uint16(product.YearManufacture.Int64)
}
if product.Desc.Valid {
newp.Desc = product.Desc.String
}
return &newp
}
}我得到了一个错误
error: scannable dest type ptr with >1 columns (5) in result这就好像Get()函数只针对一列。但是文档清楚地指出它不是!
如果我将Get()函数调用更改为Psqldb.QueryRowx(QUERY_SELECT_PRODUCT, productId).StructScan(product)
那么它确实起作用了..但还是..。试图找出Get()不能工作的原因。
接下来..。Select()
这就是结构
type PsqlCategory struct {
Id int64 `db:"category_id"`
Name string `db:"category_name"`
ParentCategoryId sql.NullInt64 `db:"parent_category_id"`
}sql查询:
QUERY_SELECT_CATEGORIES = `
select category.id as category_id,
text_translation.text as category_name,
category.parent_category_id
from category
join text_translation on text_translation.text_id=category.category_name_trans_id
and text_translation.lang_id = 1`和函数
func PsqlGetCategories() []Category {
categories := []PsqlCategory{}
err := Psqldb.Select(&categories, QUERY_SELECT_CATEGORIES)
if err != nil {
log.Fatalf("could not parse categories: %v", err)
return nil
}
var nCategories []Category
for _, cat := range categories {
newCat := Category{
Id: cat.Id,
Name: cat.Name,
}
if cat.ParentCategoryId.Valid {
newCat.ParentCategoryId = cat.ParentCategoryId.Int64
}
nCategories = append(nCategories, newCat)
}
return nCategories
}这就是错误
could not parse categories: pq: relation "category" does not exist好像我完全误解了sqlx库的用法,或者我遗漏了什么。
任何关于这个问题的信息都将不胜感激。
发布于 2018-08-26 02:09:14
出现这个问题是因为您将**PsqlProduct传递给Get,它认为您想要将查询结果扫描到指向的指针,因此是"... dest type ptr with >1 columns ..."。
只需更改:
err := Psqldb.Get(&product, QUERY_SELECT_PRODUCT,productId)至:
err := Psqldb.Get(product, QUERY_SELECT_PRODUCT,productId)https://stackoverflow.com/questions/52018701
复制相似问题