亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果未找到行,QueryRow().Scan() 將返回錯誤。怎么解決?

如果未找到行,QueryRow().Scan() 將返回錯誤。怎么解決?

Go
qq_笑_17 2023-07-10 16:46:35
我花了很多時間試圖解決這個問題。我有一個結構:type Token struct {    Id             *int64     `db:"id"`    Email          *string    `db:"email"`    OperationType  *string    `db:"operation_type"`    Token          *string    `db:"token"`    ExpirationDate *time.Time `db:"expiration_date"`}我有一個通過電子郵件查找一個令牌的函數:func (r Repo2) FindOneByEmail(ctx context.Context, email string, ct *Token) error {    row := r.DB.QueryRow(`        SELECT id, email, operation_type, token, expiration_date         FROM tokens         WHERE email=$1 AND type=$2 AND expiration_date>$3::date`,        email, "registration", time.Now(),    )    err := row.Scan(&ct.Id, &ct.Email, &ct.OperationType, &ct.Token, &ct.ExpirationDate)    if err != nil {        return err    }    return nil}db 中的某些字段可以為空(這就是我在結構中使用指針的原因)但是當我執行 .Scan 時,它會拋出錯誤(因為值為空,所以它不能采用地址“&”)但是如果我刪除“&”,它也會拋出錯誤“無效的內存地址或零指針取消引用”那么我該如何解決這個問題呢?想法是:如果找到一行,則需要獲取字段值,但如果未找到行,則需要拋出 sql.ErrNoRows
查看完整描述

1 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

pgx驅動解決方案:


從結構中刪除指針


type Token struct {

    Id             int64     `db:"id"`

    Email          string    `db:"email"`

    OperationType  string    `db:"operation_type"`

    Token          string    `db:"token"`

    ExpirationDate time.Time `db:"expiration_date"`

}

重寫功能


func (r Repo2) FindOneByEmail(ctx context.Context, email string, ct *Token) error {

    var date pgtype.Timestamptz


    row := r.DB.QueryRow(`

        SELECT id, email, operation_type, token, expiration_date 

        FROM tokens 

        WHERE email=$1 AND type=$2 AND expiration_date>$3::date`,

        email, "registration", time.Now().UTC(),

    )


    err := row.Scan(&ct.Id, &ct.Email, &ct.OperationType, &ct.Token, &date)

    if err != nil {

        return err

    }


    ct.ExpirationDate = date.Time


    return nil

}


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號