6

如何解決 Mysql2::Error: Incorrect string value

 2 years ago
source link: https://blog.niclin.tw/2019/02/26/%E5%A6%82%E4%BD%95%E8%A7%A3%E6%B1%BA-mysql2error-incorrect-string-value/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Nic Lin's Blog

喜歡在地上滾的工程師

在 mysql 裡面要注意 character 的設定,否則會發生儲存錯誤的情況發生,今天在本機開發時一切正常,上 production 跑完 migrate 後新增資料就炸了

Mysql Incorrect string value '\xE7\xA8\x8B\xE5\xBA\x8F...' for column 'course' at row 1

滿頭問號,看了 rails 的 schema 確認是 utf8 沒錯,但其實這裡的 schema 是本機生成的,所已有可能 production 上面的不是?

後來追了一下,發現原來這個 database 有歷史共業,當初在開設的時候設成 latin1,所以新建的 table 想當然爾如果沒特別設定就沒辦法存中文字了。

最快的解法,進 rails console

ActiveRecord::Base.connection.execute("ALTER TABLE 「表的名字」 CONVERT TO CHARACTER SET utf8;")

這樣就搞定了,不過 MySQL 的 utf8 並不是真的 utf8(這裡因為和其他資料表一致,就先這樣設定了),嚴格來講應該要用 utf8mb4下一篇在解釋好了。

還有一個方法可以在跑 migrate 時直接設定 character, 在 create_table 後面加入 options 就行了。

create_table "groups", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
  t.integer  "name"
end

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK