duaabhuv188411 2018-02-01 16:19
浏览 37
已采纳

在应用程序中处理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 2018-02-02 11:02
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档