9
5

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.

structではなくinterfaceにScanした値を入れる

Last updated at Posted at 2016-08-28

__Gorm__や__sqlx__のようなGolangのデータベースライブラリではプリミティブな機能である(*DB) Rows(*Rows) Scanが使用できる。
(*Rows) Scanの引数は大抵の場合structで紹介されているがinterface{}にScanした値をいれることができる。

以下がスニペット。


rows, err := sql.Rows()

var results []map[string]interface{}
cols, err := rows.Columns()

for rows.Next() {
	var row = make([]interface{}, len(cols))
	var rowp = make([]interface{}, len(cols))
	for i := 0; i < len(cols); i++ {
		rowp[i] = &row[i]
	}

	rows.Scan(rowp...)

	rowMap := make(map[string]interface{})
	for i, col := range cols {
		switch row[i].(type) {
		case []byte:
			row[i] = string(row[i].([]byte))
			num, err := strconv.Atoi(row[i].(string))
			if err == nil {
				row[i] = num
			}
		}
		rowMap[col] = row[i]
	}

	results = append(results, rowMap)
}

9
5
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
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?