3
3

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言語で発生する「sql: Scan error on column index」の捌き方

Posted at

エラー発生

sql: Scan error on column index 7, name "cfn_stack_name": unsupported Scan, storing driver.Value type <nil> into type *string

Go言語でプログラミングで
DBにアクセスする処理を記述していると
上記のエラーに遭遇する事がある。

多くの原因はSQLのSELECT結果でカラムからNULLが取得され、
Go言語のstring型がNULLに対応していない事が原因です。

対応方法

調査したところ下記のような対応方法がありました。
https://qiita.com/kotamat/items/e6dd5806e52939d28043
https://qiita.com/kkam0907/items/f23efade4b7fbadebb5a

別解

Go言語内の実装で対応しても良いのですが、
手っ取り早くSQLでNULLを取得する可能性があるカラムを
IFNULL関数で空文字に変換する方法もあります。

example
SELECT ID,IFNULL(UserName,'') FROM User_Table

上記の例ではUserNameのカラムがNULLを返す可能性がある為、
IFNULL関数を使用してNULLを空文字に変換しています。
空文字であればGo言語のstring型は対応しています。

MySQLの場合はIFNULLだが
PostgreSqlの場合はCOALESCE
Oracleの場合はNVL
など微妙に使い方が違う点に注意

[参照]
https://yamasakimasaki.com/blog/121.html

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?