Golang Insert NULL into sql instead of empty string

前端 未结 2 1937
时光说笑
时光说笑 2021-02-02 08:39

I\'m trying to insert data into a mysql database using golang. In the case where my value takes on an empty string, I would want to insert a null. How can I adjust the following

2条回答
  •  生来不讨喜
    2021-02-02 09:27

    The database/sql package has a NullString type (docs) for just this situation.

    Basically just use sql.NullString in place of strings where you want them to be nullable in db.

    You could also use a *string in your code to the same effect.

    The problem in either case is in mapping to/from a nullable string to a non-nullable string. The empty string is technically a value, so you will almost always have to do something like this if you decide empty string should be translated to nil:

    nullableS := &s
    if s == "" {
      nullableS = nil
    }
    

    The alternative would be to just use *string instead of string in your models throughout your app.

    In databases, I have been taking the approach that empty string and null are equivalent, and just storing empty sting in the db, and making most columns non-nullable.

提交回复
热议问题