duaabhuv188411
duaabhuv188411
2018-02-01 16:19

在应用程序中处理NULL值并发送到数据库

已采纳

I have nullable variables I'm trying to use in my app, and also send to a database which has columns that are default null.

This is a sample struct:

// Location type
type Location struct {
    ID      int `schema:"id"`
    Title   *string `schema:"title"`
}

Title is defined as *string, as it could be null (e.g. no user input or client app sends it as null).

Here’s my function receiving form data:

// JSONLocationCreate func
func (a *App) JSONLocationCreate(w http.ResponseWriter, r *http.Request) {

    r.ParseForm()

    var e Location

    err := decoder.Decode(&e, r.PostForm)
    if err != nil {
        respondWithError(w, http.StatusBadRequest, "Invalid request payload")
        return
    }


    // --- SUCCESS ---
    // If e.Title has data, the following line works.

    // --- FAIL ---
    // If e.Title doesn’t have data (for whatever reason), it’s null, and crashes the app:
    log.Println(*e.Title)


    // Ultimately the variable would be sent off to a database.
    // Below I’m removing other functions and such, just including my statement line.


    // --- SUCCESS ---
    // If e.Title has data, the following line works.

    // --- FAIL ---
    // If e.Title is null (e.g. no user input), this crashes the app.
    statement := fmt.Sprintf("INSERT INTO locations(title) VALUES('%s')", *e.Title)

    // In either case, the crash error is similar to this:
    // panic serving [::1]:52459: runtime error: invalid memory address or nil pointer dereference
}

CONCERN 1: How can I make use of nullable variables (like e.Title), throughout the app, without throwing panic errors when the variable is null? Is the best practice to wrap it in a function that converts null to “” strings? How can such a function be applied transparently, so I don’t have to have something like “nullCheck(*e.Title)” on every instance of the variable?

CONCERN 2: In the case of my DB queries, I can’t be sending “” string values into the database in place of nulls. Up to now my queries are manually built. I suppose I need a function to generate the SQL queries automatically excluding columns and variables when the variables are null.

Am I on the right track? Any examples?

I haven’t understood all the threads/tutorials after hours of searching.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqin7086 douqin7086 3年前

    CONCERN 1 is easily remedied by adding a getter method for your fields

    func (l Location) GetTitle() string {
        if l.Title == nil {
            return ""
        }
        return *l.Title
    }
    

    CONCERN 2: It depends on what sql queries do you want to make, I would suggest that you look into some ORM libraries, which automate a lot of DB-specific code for you. Gorm is a good example of such library: https://github.com/jinzhu/gorm

    点赞 评论 复制链接分享