title: Function in Go to execute select query on database and return json output
body: <p>I am writing a function in Go to execute select query on database.</p>
  
  <p><strong>Input:</strong> String e.g. "Select id, name, age from sometable"
  This query changes everytime.</p>
  
  <p><strong>Output:</strong> Output of select query in json format.</p>
  
  <p><strong>Sample Expected output:</strong> {"Data":[{"id":1,"name":"abc", "age":40},{"id":2,"name":"xyz", "age":45}]}</p>
  
  <p><strong>Sample Actual output:</strong> {"Data":[[1,"abc",40],[2,"xyz",45]]}</p>
  
  <p>Instead of i.e. column_name:value, I get only values. 
  How do I get the expected output?</p>
  
  <pre><code>func executeSQL(queryStr string) []byte {
  connString := createConnectString()
  conn, err := sql.Open("mssql", connString)
  if err != nil {
      log.Fatal("Error while opening database connection:", err.Error())
  }
  defer conn.Close()
  
  rows, err := conn.Query(queryStr)
  if err != nil {
      log.Fatal("Query failed:", err.Error())
  }
  defer rows.Close()
  
  columns, _ := rows.Columns()
  count := len(columns)
  
  var v struct {
      Data []interface{} // `json:"data"`
  }
  
  for rows.Next() {
      values := make([]interface{}, count)
      valuePtrs := make([]interface{}, count)
      for i, _ := range columns {
          valuePtrs[i] = &amp;values[i]
      }
      if err := rows.Scan(valuePtrs...); err != nil {
          log.Fatal(err)
      }
      v.Data = append(v.Data, values)
  }
  jsonMsg, err := json.Marshal(v)
  return jsonMsg
  }
  </code></pre>