postgresql - 扫描到其中一些是指针的结构字段
问题描述
我正在编写一个 GO 应用程序,并试图找到一种简单的方法来扫描数据库中的一行到结构字段。
我使用 pgx 连接到 postgresql 数据库
gqlgen 生成了这个类:
type Profile struct {
Name string `json:"name"`
JoinedAt time.Time `json:"joined_at"`
Bio *string `json:"bio"`
}
然后我得到了从数据库获取用户配置文件的功能:
func GetUserProfile(ctx context.Context, profileDir string) (*model.Profile, error) {
sqlQuery := `select name,joined_at::timestamptz,bio from foo where profile_dir=$1`
var profile model.Profile
if err := Connection.QueryRow(ctx, sqlQuery, profileDir).
Scan(&profile.Name, &profile.JoinedAt, &profile.Bio); err != nil {
return nil, err
} else {
return &profile, nil
}
}
现在因为Bio
是一个指针,我需要创建一个不是指针的变量,扫描它并将其地址分配给结构:
var profile model.Profile
var mybio string
...
Connection.QueryRow(...).Scan(...,&mybio)
profile.Bio=&mybio
有没有更简单的方法来扫描一行到可能有指针的结构?
解决方案
如果Bio
已经是一个指针,则不需要在 Scan 调用中使用额外的指针:
profile := Profile{
Bio: new(string),
}
if err := Connection.QueryRow(ctx, sqlQuery, profileDir).
Scan(&profile.Name, &profile.JoinedAt, profile.Bio); err != nil {
return nil, err
} else {
return &profile, nil
}
推荐阅读
- php - PHP如何将url清理为重定向
- pandas - 如何链接 pandas.read_sql_query 的命令?
- android - 支持库版本 28.0.0 TabLayout 错误
- vba - VBA EXCEL:当值更改为我的宏时,添加突出显示单元格的可能性
- singlestore - 如何在 memsql 中查询“select ... for update” mysql 查询?不可能吗?
- php - 我不知道如何测试创建查询生成器
- python - 基于广播变量的pyspark过滤数据帧
- corda - 在 Corda 中,什么使合同具有法律约束力?
- c# - 2 多维数组中的值搜索
- python-3.x - Pod 内存使用量无限增长