如何在Golang中從資料庫行建立映射
在database/sql包中,Rows.Scan()函數需要一個與查詢中的列匹配的特定參數數量。當處理未知或變化的資料集時,這可能會受到限制。要以更通用的方式從資料庫行建立映射,請考慮以下方法:
使用 sqlx 函式庫
sqlx 函式庫提供了 database/sql的替代方案簡化從資料庫建立地圖任務的套件rows:
// Define the function to create a map from rows func RowsToMap(rows *sql.Rows) ([]map[string]interface{}, error) { // Define the list to store the data data := []map[string]interface{}{} // Get the column names columns, err := rows.Columns() if err != nil { return nil, err } // Create a slice of interface{} to hold the data for each row values := make([]interface{}, len(columns)) // Create a slice of pointers to the values valuePtrs := make([]interface{}, len(columns)) for i, _ := range values { valuePtrs[i] = &values[i] } // Loop through the rows and add to the data list for rows.Next() { // Scan the row into the values slice err = rows.Scan(valuePtrs...) if err != nil { return nil, err } // Create a map to hold the data for the row row := make(map[string]interface{}) // Add the column names and values to the map for i, column := range columns { row[column] = values[i] } // Add the row map to the data list data = append(data, row) } return data, nil }
用法:
// Execute a query and get the rows rows, err := db.Query("SELECT * FROM mytable") if err != nil { // Handle error } // Create a map from the rows data, err := RowsToMap(rows) if err != nil { // Handle error } // Use the data as needed for _, row := range data { fmt.Println(row) }
此方法可讓您從資料庫列建立映射,而無需事先指定列名稱或類型。
以上是如何有效率地將資料庫行映射到Golang中的地圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文討論了GO的反思軟件包,用於運行時操作代碼,對序列化,通用編程等有益。它警告性能成本,例如較慢的執行和更高的內存使用,建議明智的使用和最佳

本文討論了GO中使用表驅動的測試,該方法使用測試用例表來測試具有多個輸入和結果的功能。它突出了諸如提高的可讀性,降低重複,可伸縮性,一致性和A

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver Mac版
視覺化網頁開發工具

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

SublimeText3 Linux新版
SublimeText3 Linux最新版

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能