1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

データベースからデータを取得する際のカラム数が可変のときの対処(Go言語)

Last updated at Posted at 2018-05-14

データベースからデータを取得する際のカラム数が可変の場合の対処

Go言語でデータベースからデータを取得する際にカラムの数がわからない場合に
どうやってとればいいのか悩んだのでメモを残します。

今回はPostgreSQLを使用していますが他のデータベースでも同じかなと。

sample.go

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

func main() {
	db, err := sql.Open("postgres", "user=postgres password=secret port=5432 host=loacalhost dbname=sample sslmode=disable")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM sample")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()

	// カラム情報を取得する
	types, _ := rows.ColumnTypes()
	// カラム数分だけポインターを保管するinterfaceを用意
	dataPtrs := make([]interface{}, len(types))

	for rows.Next() {
		// カラム数分だけデータ保管用のinterfaceを用意
		data := make([]interface{}, len(types))
		// ポインターを入れる
		for i := range data {
			dataPtrs[i] = &data[i]
		}
		if err := rows.Scan(dataPtrs...); err != nil {
			fmt.Println(err)
		}
		fmt.Printf("%+v\n", data)
	}
	return
}

ポイントとしてはinterfaceのポインターをinterfaceのデータにそれぞれ入れるところ。
こうすることでポインターの個所にデータをうまい具合に保存してくれます。

どのようにデータの変換や保管が行われているかについては
database/sql/convert.goのconvertAssign関数を読んでいただければと思います。

もっといい方法があればコメントいただけると助かります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?