douying6206 2019-09-20 08:58
浏览 873

将json字符串保存在Mysql文本类型字段中

I am trying to insert a record with JSON string as a value of a column in MySQL. Other columns values inserted correctly but the JSON string column does not get inserted. What does I need to achieve this?

This is the snippet where I am building the entity for saving in the DB

package main

import (
    "encoding/json"
    "fmt"
    "gocode/os/os-server/model"
)

type Deftheme struct {
    AwayIndicator string `json:"awayIndicator"`
    ButtonBg string `json:"buttonBg"`
    ButtonColor string `json:"bttonColor"`
    CenterChannelBg string `json:"centerChannelBg"`
    CenterChannelColor string `json:"centerChannelColor"`
    CodeTheme string `json:"codeTheme"`
    DndIndicator string `json:"dndIndicator"`
    ErrorTextColor string `json:"errorTextColor"`
    Image string `json:"image"`
    LinkColor string `json:"linkColor"`
    MentionBg string `json:"mentionBg"`
    MentionColor string `json:"mentionColor"`
    MentionHighlightBg string `json:"mentionHighlightBg"`
    MentionHighlightLink string `json:"mentionHighlightLink"`
    NewMessageSeparator string `json:"newMessageSeparator"`
    OnlineIndicator string `json:"onlineIndicator"`
    SidebarBg string `json:"sidebarBg"`
    SidebarHeaderBg string `json:"sidebarHeaderBg"`
    SidebarHeaderTextColor string `json:"sidebarHeaderTextColor"`
    SidebarText string `json:"sidebarText"`
    SidebarTextActiveBorder string `json:"sidebarTextActiveBorder"`
    SidebarTextActiveColor string `json:"sidebarTextActiveColor"`
    SidebarTextHoverBg string `json:"sidebarTextHoverBg"`
    SidebarUnreadText string `json:"sidebarUnreadText"`
    Type string `json:"type"`
}

func main() {
    m := Deftheme{"#c1b966", "#0177e7", "#ffffff", "#1f1f1f", "#dddddd","monokai","#e81023","#ff6461","/static/files/37bdb7f8db233daef529366b5772bb3f.png","#0d93ff","#0177e7","#ffffff","#784098","#a4ffeb","#cc992d","#399fff","#171717","#1f1f1f","#ffffff","#ffffff","#196caf","#ffffff","#302e30","#ffffff","Windows Dark"}
    b,_ := json.Marshal(m)

    default_theme_pref := model.Preference{UserId: ruser.Id, Category: model.PREFERENCE_CATEGORY_THEME, Name: '', Value: string(b)}
    if err := a.Srv.Store.Preference().Save(&model.Preferences{default_theme_pref}); err != nil {
        mlog.Error(fmt.Sprintf("Encountered error saving theme preference, err=%v", err.Message))
    }

}

And the store function where saving functionality is defined

func (s SqlPreferenceStore) Save(preferences *model.Preferences) *model.AppError {
    // wrap in a transaction so that if one fails, everything fails
    transaction, err := s.GetMaster().Begin()
    if err != nil {
        return model.NewAppError("SqlPreferenceStore.Save", "store.sql_preference.save.open_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
    }

    defer finalizeTransaction(transaction)
    for _, preference := range *preferences {
        if upsertResult := s.save(transaction, &preference); upsertResult.Err != nil {
            return upsertResult.Err
        }
    }

    if err := transaction.Commit(); err != nil {
        // don't need to rollback here since the transaction is already closed
        return model.NewAppError("SqlPreferenceStore.Save", "store.sql_preference.save.commit_transaction.app_error", nil, err.Error(), http.StatusInternalServerError)
    }
    return nil
}

func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *model.Preference) store.StoreResult {
    result := store.StoreResult{}

    preference.PreUpdate()

    if result.Err = preference.IsValid(); result.Err != nil {
        return result
    }

    params := map[string]interface{}{
        "UserId":   preference.UserId,
        "Category": preference.Category,
        "Name":     preference.Name,
        "Value":    preference.Value,
    }

    if s.DriverName() == model.DATABASE_DRIVER_MYSQL {
        if _, err := transaction.Exec(
            `INSERT INTO
                Preferences
                (UserId, Category, Name, Value)
            VALUES
                (:UserId, :Category, :Name, :Value)
            ON DUPLICATE KEY UPDATE
                Value = :Value`, params); err != nil {
            result.Err = model.NewAppError("SqlPreferenceStore.save", "store.sql_preference.save.updating.app_error", nil, err.Error(), http.StatusInternalServerError)
        }
    } else {
        result.Err = model.NewAppError("SqlPreferenceStore.save", "store.sql_preference.save.missing_driver.app_error", nil, "Failed to update preference because of missing driver", http.StatusNotImplemented)
    }

    return result
}

My table structure looks like

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| UserId   | varchar(26) | NO   | PRI | NULL    |       |
| Category | varchar(32) | NO   | PRI | NULL    |       |
| Name     | varchar(32) | NO   | PRI | NULL    |       |
| Value    | text        | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

I am getting the following errors

app/user.go:369:102: cannot use '\u0000' (type rune) as type string in field value
app/user.go:369:109: empty character literal or unescaped ' in character literal
app/user.go:369:112: cannot use def_theme_data (type []byte) as type string in field value
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 求三轴之间相互配合画圆以及直线的算法
    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 自己瞎改改,结果现在又运行不了了
    • ¥15 链式存储应该如何解决
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站