使用帶有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中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境