0
0

More than 1 year has passed since last update.

gormでtime.Time型を使用する

Posted at

gormでレコード取得をする際に以下のエラーが出ました。

sql: Scan error on column index 3, name \"updated_at\": unsupported Scan, storing driver.Value type []uint8 into type *time.Time

updated_atカラムの型をサポートしてない的なことが書いてあるので少し調べました。

解決策

gormの公式ドキュメントにも記載がありましたが、
time.Time型を扱うには、接続時のDSN情報にparseTimeを指定する必要がありました。

注 time.Time を正しく処理するには、パラメータとして parseTime を含める必要があります。 (その他のパラメータ) UTF-8 エンコーディングを完全にサポートするには、 charset=utf8 を charset=utf8mb4 に変更する必要があります。

goのsqlドライバのgithubにも詳細が記載されていましたが、
parseTime=trueと指定をすることで、DATETIME型のデータをtime.Time型に変換してくれるそうです。

parseTime=true changes the output type of DATE and DATETIME values to time.Time instead of []byte / string The date or datetime like 0000-00-00 00:00:00 is converted into zero value of time.Time.

parseTime=trueは、DATEおよびDATETIME値の出力タイプを[]byte / stringの代わりにtime.Timeに変更します。0000-00-00 00:00:00のような日付または日時は、time.Timeのゼロ値に変換されます。

なので接続時のDSN情報にparseTime=trueを追加するだけで問題なく解決できました。

dsn := "root:root@tcp(127.0.0.1:3306)/db_name?charset=utf8&parseTime=true"

参考

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