首頁 > 後端開發 > Golang > 主體

如何在 Go MySQL 查詢中使用 SET 變數?

Patricia Arquette
發布: 2024-10-23 17:49:02
原創
395 人瀏覽過

How to Use SET Variables in Go MySQL Queries?

使用帶有SET 變數的Go MySQL 查詢

您正在嘗試編寫一個Go MySQL 查詢來設定變數並在複雜的環境中使用它們ORDER BY 子句。查詢在控制台中成功運行,但在 Go 中遇到語法錯誤。

可能的解決方案

不幸的是,Go 的資料庫/sql 套件目前不支援設定 MySQL 使用者-定義的變數。因此,問題中描述的方法在包的當前限制下不可行。

替代方法

動態查詢產生:

一個替代方案是根據輸入參數動態產生ORDER BY 子句,從而無需進行變數替換。

<code class="go">func (d *DB) SelectByUserId(uid string, srt string, pg, lim int) ([]Inventory, error) {
    query := `
    SELECT
        *
    FROM
        inventory
    WHERE
        user_id = ?
    ORDER BY
        ` + generateOrderBy(srt) + `
    LIMIT ?,?;
    `

    rows, err := d.Query(
        query,
        uid,
        pg*lim,
        lim,
    )

    // ... (rest of the code remains the same)

    return result, nil
}

func generateOrderBy(srt string) string {
    order := ""
    switch srt {
    case "type,asc":
        order = "`type` ASC"
    case "type,desc":
        order = "`type` DESC"
    // ... (add other cases)
    }
    return order
}</code>
登入後複製

參數擴充:

或者,您可以手動擴充 ?查詢字串中的佔位符以避免需要變數。這種方法涉及建立一個字串來替換每個 ?與相應的參數值。

<code class="go">func (d *DB) SelectByUserId(uid string, srt string, pg, lim int) ([]Inventory, error) {
    query := fmt.Sprintf(`
    SELECT
        *
    FROM
        inventory
    WHERE
        user_id = '%s'
    ORDER BY
        CASE WHEN '%s' = 'type,asc' THEN `type` END,
        CASE WHEN '%s' = 'type,desc' THEN `type` END DESC,
        CASE WHEN '%s' = 'visible,asc' THEN visible END,
        CASE WHEN '%s' = 'visible,desc' THEN visible END DESC,
        CASE WHEN '%s' = 'create_date,asc' THEN create_date END,
        CASE WHEN '%s' = 'create_date,desc' THEN create_date END DESC,
        CASE WHEN '%s' = 'update_date,asc' THEN update_date END,
        CASE WHEN '%s' = 'update_date,desc' THEN update_date END DESC
    LIMIT %d,%d;
    `, uid, srt, srt, srt, srt, srt, srt, srt, srt, pg*lim, lim)

    rows, err := d.Query(
        query,
    )

    // ... (rest of the code remains the same)

    return result, nil
}</code>
登入後複製

以上是如何在 Go MySQL 查詢中使用 SET 變數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!