Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Go's Rows.Scan ignore fields from SQL query

Tags:

go

cockroachdb

The Rows.Scan method takes as many parameters as there are columns in the SQL query.

As the query being executed is SHOW COLUMNS FROM my_table I cannot omit any column which I don't require (or can I?).

Is there any way to ignore some fields from the query result set which is not required?

Below is my code:

rows, err := db.Query("SHOW COLUMNS FROM " + r.Name)
DieIf(err)
//var field, dataType, ignoreMe1, ignoreMe2, ignoreMe3 string
var field, dataType string
for rows.Next() {
                    //This Place
                    //   |
                    //   V
    if err := rows.Scan(&field, &dataType); err != nil {
        DieIf(err)
    }
    r.Attributes[field] = Attribute{
        Name:       field,
        DataType:   dataType,
        Constraint: false,
    }
}

error: sql: expected 5 destination arguments in Scan, not 2

like image 922
Pallav Jha Avatar asked Oct 29 '22 03:10

Pallav Jha


1 Answers

So here I'm with one solution for you, try this one to get field and type from query.

package main

import (
    "fmt"
    _ "github.com/lib/pq"
    "database/sql"
)

func main() {

    db, _ := sql.Open(
        "postgres",
        "user=postgres dbname=demo password=123456")

    rows, _ := db.Query("SELECT * FROM tableName;")

    columns, _ := rows.Columns()
    count := len(columns)
    values := make([]interface{}, count)
    valuePtr := make([]interface{}, count)

    for rows.Next() {

        for i, _ := range columns {
            valuePtr[i] = &values[i]
        }

        rows.Scan(valuePtr...)

        for i, col := range columns {

            var v interface{}

            val := values[i]

            b, ok := val.([]byte)

            if (ok) {
                v = string(b)
            } else {
                v = val
            }

            fmt.Println(col, v)
        }
    }
}
like image 123
saddam Avatar answered Jan 02 '23 20:01

saddam