Golang: Store Query Result in a Map

目录

  • 1. Golang: Store Query Result in a Map
    • 1.1. Using Structs
    • 1.2. Using Maps

1. Golang: Store Query Result in a Map

注意: 使用这个可能会造成列名和列值乱串的现象,解决这个可以使用 AS 语法:

SELECT TENANT_ID AS TENANT_ID,SVR_IP AS SVR_IP,SVR_PORT AS SVR_PORT,PLAN_ID AS PLAN_ID,SQL_ID AS SQL_ID,TYPE AS TYPE,DB_ID AS DB_ID,STATEMENT AS STATEMENT,PLAN_HASH AS PLAN_HASH,LAST_ACTIVE_TIME AS LAST_ACTIVE_TIME,ELAPSED_TIME AS ELAPSED_TIME
FROM GV$PLAN_CACHE_PLAN_STAT
WHERE LAST_ACTIVE_TIME > '%s' AND LAST_ACTIVE_TIME <= '%s' AND ELAPSED_TIME > %d

Converting the results of a SQL query to a struct in Go is trivial, but sometimes you don’t know ahead of time exactly what columns and types you’re going to be retrieving, and a map may be better suited for storing the results.

1.1. Using Structs

First, here’s the standard way we can convert results to a struct:

rows, _ := db.Query("SELECT ...") // Note: Ignoring errors for brevity
for rows.Next() {s := myStruct{}if err := rows.Scan(&s); err != nil {return err}// Do something with 's'
}

Easy enough, but storing your query result in a map is a bit trickier.

1.2. Using Maps

Let’s say for example you’re working with a user’s database where you don’t know the schema ahead of time. You can’t write a struct to store the results, because you don’t know what columns and data types you’re going to be retrieving. What we want in this case is a map[string]interface{} where the key is the column name and the value could be any data type.

You might assume you can do the following:

rows, _ := db.Query("SELECT ...") // Note: Ignoring errors for brevity
for rows.Next() {m := make(map[string]interface{})// This WON'T WORKif err := rows.Scan(&m); err != nil {// ERROR: sql: expected X destination arguments in Scan, not 1}
}

Basically the SQL package is thinking that you expect a single column to be returned and for it to be a map[string]interface{} compatible type, which isn’t what we we’re trying to do.

Instead what we have to do in order to make this work is the following:

rows, _ := db.Query("SELECT ...") // Note: Ignoring errors for brevity
cols, _ := rows.Columns()for rows.Next() {// Create a slice of interface{}'s to represent each column,// and a second slice to contain pointers to each item in the columns slice.columns := make([]interface{}, len(cols))columnPointers := make([]interface{}, len(cols))for i, _ := range columns {columnPointers[i] = &columns[i]}// Scan the result into the column pointers...if err := rows.Scan(columnPointers...); err != nil {return err}// Create our map, and retrieve the value for each column from the pointers slice,// storing it in the map with the name of the column as the key.m := make(map[string]interface{})for i, colName := range cols {val := columnPointers[i].(*interface{})m[colName] = *val}// Outputs: map[columnName:value columnName2:value2 columnName3:value3 ...] fmt.Print(m)
}

So how does this work? Well first we query and get our rows as usual, but this time we use rows.Columns() to get a reference to all column names in the result.

Then for each row, we create a slice of interface{}’s called columns who’s length matches the number of columns. Next we create a second slice with the same length called columnPointers, but this time we iterate over each element in columns and store a pointer to the interface{} element in our columnPointers slice. This is necessary because the sql package requires pointers when scanning. So now we have two slices, one of interface{}s and one of pointers to the interface{}s.

Now we can scan the row into the slice of interface{} pointers (ie. columnPointers).

Finally, we create our map[string]interface{}, and iterate over the column names. For each column name (colName), we deference the interface{} pointer at the current loop index from the columnPointers slice, which references the value in the columns slice. We take this dereferenced value and store it in the map as the value, with the key being the column name.

Now we can use the map however we need, essentially allowing us to perform queries dynamically, without requiring knowledge of the schema we’re going to be querying when we write our code.

This may seem a little confusing at first, especially if you have no prior experience with pointers. If so, I’d recommend reading up on Pointers and trying the code out, inserting some debug logging to fully understand what’s happening during each step of the process.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/151978.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

程序员导航站

探路者 hello.alluniverse.vip 开发者导航 - Pro Developer网站导航 探路者是一款极简导航工具&#xff0c;致力于收录的每个站点都有其独特的作用。同时支持自定义导航&#xff0c;让用户快速实现个性化的导航站点。 特性概述 免费ChatGPT 装机必备 开发工具 Git精选项目 …

LabVIEW编程开发NI-USRP

LabVIEW编程开发NI-USRP 可编程性是SDR的关键特性&#xff0c;它使人们能够将无线电外围设备转换为先进的无线系统。USRP是市场上最开放、最通用的SDR&#xff0c;可帮助工程师在主机和FPGA上使用各种软件开发工具构建系统。 有多种选项可用于对基于SDR的系统的主机进行编程。…

9 HDFS架构剖析

问题 100台服务器&#xff0c;存储空间单个200GB 20T 5T文件如何存储&#xff1f; 128MB一块 128MB81GB 1288*10241TB 5T数据分成的128MB的块数 8192 * 5 客户端(client)代表用户通过与namenode和datanode交互来访问整个文件系统。 HDFS集群有两类节点&#xff1a; 一个na…

Python武器库开发-flask篇之error404(二十七)

flask篇之error404(二十七) 首先&#xff0c;我们先进入模板的界面创建一个404的html页面 cd templates vim 404.html404.html的内容如下&#xff1a; <h1>error!!!</h1>在 Flask 应用程序中&#xff0c;当用户访问一个不存在的页面的时候&#xff0c;会出现 4…

MAC上修改mysql的密码(每一步都图文解释哦)

当你想要连接本机数据库时&#xff0c;是不是有可能突然忘记了自己的数据库密码? 在此文中&#xff0c;我们来详细解决一下如何去修改自己的数据库密码&#xff0c;并使用Navicat来连接测试 1.停止mysql服务 打开终端&#xff0c;键入命令,将mysql服务先停止掉&#xff0c;…

JC/T 2339-2015 地暖用相变储能材料及构件检测

相变储能材料是指利用相变过程吸收/释放热量并能与地暖配套使用的材料及构件。 JC/T 2339-2015 地暖用相变储能材料及构件测试项目 测试项目 测试标准 相变温度 JC/T 2111 相变潜热 JC/T 2111 材料寿命 JC/T 2339 单位面积相变储能量 JC/T 2339 耐冷循环性能 JC/T …

归并排序详解:递归实现+非递归实现(图文详解+代码)

文章目录 归并排序1.递归实现2.非递归实现3.海量数据的排序问题 归并排序 时间复杂度&#xff1a;O ( N * logzN ) 每一层都是N,有log2N层空间复杂度&#xff1a;O&#xff08;N&#xff09;&#xff0c;每个区间都会申请内存&#xff0c;最后申请的数组大小和array大小相同稳定…

智能指针面试题

智能指针被问到的概率还是很大的&#xff0c;特别是Shared_ptr&#xff0c;最好会手撕&#xff0c;亲身经历&#xff01; 基本概念 1. RAll RAII&#xff08;Resource Acquisition Is Initialization&#xff09;是一种利用对象生命周期来控制程序资源&#xff08;如内存、文…

(Transfer Learning)迁移学习在IMDB上训练情感分析模型

1. 背景 有些场景下&#xff0c;开始的时候数据量很小&#xff0c;如果我们用一个几千条数据训练一个全新的深度机器学习的文本分类模型&#xff0c;效果不会很好。这个时候你有两种选择&#xff0c;1.用传统的机器学习训练&#xff0c;2.利用迁移学习在一个预训练的模型上训练…

Python如何实现原型设计模式?什么是原型设计模式?Python 原型设计模式示例代码

什么是原型&#xff08;ProtoType&#xff09;设计模式&#xff1f; 原型模式&#xff08;Prototype Pattern&#xff09;是一种创建型设计模式&#xff0c;旨在通过复制现有对象来创建新对象&#xff0c;而无需通过标准的构造方式。它允许我们基于现有对象创建新对象&#xf…

PHPmail 发送邮件错误 550 的原因是什么?

电子邮件错误消息链接到简单邮件传输协议 (SMTP)&#xff0c;这是一组发送和接收电子邮件的标准化规则。因此&#xff0c;它也称为 SMTP 550 错误代码。在某些情况下&#xff0c;电子邮件错误 550 是由收件人一方的问题引起的。 以下是电子邮件错误 550 的一些可能原因&#x…

MFC/QT 一些快要遗忘的细节:

1&#xff1a;企业应用中&#xff0c;MFC平台除了用常见的对话框模式还有一种常用的就是单文档模式&#xff0c; 维护别人的代码&#xff0c;不容易区分,其实找与程序同名的cpp就知道了&#xff0c;比如项目名称为 DoCMFCDemo&#xff0c;那么就看BOOL CDocMFCDemoApp::InitI…

代码随想录算法训练营第23期day59|503.下一个更大元素II、42. 接雨水

一、503.下一个更大元素II 力扣题目链接 可以不扩充nums&#xff0c;在遍历的过程中模拟走两边nums class Solution { public:vector<int> nextGreaterElements(vector<int>& nums) {vector<int> result(nums.size(), -1);if (nums.size() 0) return…

外贸自建站什么意思?自建独立网站的好处?

外贸自建站的含义是什么&#xff1f;如何区分自建站和独立站&#xff1f; 随着全球贸易的不断发展&#xff0c;越来越多的企业开始关注外贸自建站。那么&#xff0c;“外贸自建站”到底是什么意思呢&#xff1f;海洋建站将为您详细解析这个问题&#xff0c;带您深入了解这一新…

Spring cloud负载均衡@LoadBalanced LoadBalancerClient

LoadBalance vs Ribbon 由于Spring cloud2020之后移除了Ribbon&#xff0c;直接使用Spring Cloud LoadBalancer作为客户端负载均衡组件&#xff0c;我们讨论Spring负载均衡以Spring Cloud2020之后版本为主&#xff0c;学习Spring Cloud LoadBalance&#xff0c;暂不讨论Ribbon…

Win10 开始菜单、微软app和设置都打不开(未解决)

环境&#xff1a; Win10专业版 问题描述&#xff1a; Win10 开始菜单、微软app和设置都打不开,桌面个性话打开就报错&#xff0c;打开个性化该文件没有与之关联的程序来执行该操作 解决方案&#xff1a; 一般造成原因是MS-Settings文件系统错误 1.先重启电脑&#xff08;重…

【开源】基于Vue.js的高校宿舍调配管理系统

项目编号&#xff1a; S 051 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S051&#xff0c;文末获取源码。} 项目编号&#xff1a;S051&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能需求2.1 学生端2.2 宿管2.3 老师端 三、系统…

Pycharm中添加Python库指南

一、介绍 Pycharm是一款为Python开发者提供的集成开发环境&#xff08;IDE&#xff09;&#xff0c;支持执行、调试Python代码&#xff0c;并提供了许多有用的工具和功能&#xff0c;其中之一就是在Pycharm中添加Python库。 添加Python库有许多好处&#xff0c;比如能够增加开…

【云栖 2023】林伟:大数据 AI 一体化的解读

云布道师 本文根据 2023 云栖大会演讲实录整理而成&#xff0c;演讲信息如下&#xff1a; 演讲人&#xff1a;林伟 | 阿里云研究员&#xff0c;阿里云计算平台事业部首席架构师&#xff0c;阿里云人工智能平台 PAI 和大数据开发治理平台 DataWorks 负责人 演讲主题&#xff1a…

推荐10 本软件架构技术的好书【赠书活动|第11期《高并发架构实战》】

相信大家都对未来的职业发展有着憧憬和规划&#xff0c;要做架构师、要做技术总监、要做CTO。对于如何实现自己的职业规划也都信心满满&#xff0c;努力工作、好好学习、不断提升自己。 文章目录 《高并发架构实战&#xff1a;从需求分析到系统设计》《架构师的自我修炼&#x…