[Mysql] Mysql Incorrect string value problem

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

同:Mysql 插入中文错误:Incorrect string value: ‘\xE7\xA8\x8B\xE5\xBA\x8F…’ for column ‘course’ at row 1

解決方式

如果資料庫已經創建,則先刪除。

1
2
mysql> show databases;
mysql> drop database wrong_database;

再重新創建,並以 utf8mb4 為預設

1
mysql> CREATE DATABASE test_database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

可以 migrate && 創建一筆數據去測試問題是否仍存在
這邊展示,用測試環境的虛擬機上跑指令:

1
2
RAILS_ENV=staging bin/rake db:migrate
RAILS_ENV=staging bin/rake db:seed

檢視 database 編碼

主要是確認 DEFAULT CHARACTER SET

1
2
mysql> create database wrong_database;
mysql> show create database wrong_database;

1
2
mysql> CREATE DATABASE test_database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
mysql> show create database test_database;

明顯看到 DEFAULT CHARACTER SET
latin1 vs utf8mb4_unicode_ci

檢視所有 column 編碼

1
mysql> SHOW FULL COLUMNS FROM name_tables;

修改 table 編碼(utf8)

和修改 database 編碼的差別就是,database 可以一勞永逸(utf8),這是暫時處理這個 table 的編碼(utf8)

1
2
# rails console
pry(main)> ActiveRecord::Base.connection.execute("ALTER TABLE name_tables CONVERT TO CHARACTER SET utf8;")
1
mysql> ALTER TABLE name_tables CONVERT TO CHARACTER SET utf8;

Ref

搜尋:檢視編碼

搜尋:mysql 使用 database 指令

StackExange

Nic

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×