我在数据库表上设置 utf8 时遇到一些问题。
我遵循了这些文件,但没有工作
pymsql 文档: https://pymysql.readthedocs.io/en/latest/modules/connections.html
皮尤文档: http://docs.peewee-orm.com/en/latest/peewee/database.html#using-mysql
这是我的代码
import datetime
from peewee import *
import pymysql
from getDataFromExcel import *
mysql_db = MySQLDatabase(
databasename,
user='username',
password='password',
host='host',
charset='utf8', # <-- what I followed from docs
)
class BaseModel(Model):
"""A base model that will use our MySQL database """
class Meta:
database = mysql_db
class Food(BaseModel):
name = CharField()
allergy = CharField()
special = CharField()
createdAt = DateTimeField(default = datetime.datetime.now)
updatedAt =DateTimeField(default = datetime.datetime.now)
class Meta:
table_name='Food'
def initialize():
"""Create the database and the table if they don't exist."""
mysql_db.connect()
print('Initialized')
def insert_food_data(food_rows):
with mysql_db.atomic():
Food.insert_many(food_rows,fields=[
Food.name,
Food.allergy,
Food.special
]).execute()
if __name__ =='__main__':
initialize()
我使用python3 -i filename.py
之后,我交互式地放置了更多代码(删除现有表并创建新表以检查utf8设置是否完成(
mysql_db.execute_sql("SET FOREIGN_KEY_CHECKS=0")
mysql_db.drop_tables([Food])
mysql_db.create_tables([Food])
但是当我使用 MySQLWorkbench 检查我的数据库时。 我桌子的 DDL 水龙头说
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`allergy` varchar(255) NOT NULL,
`special` varchar(255) NOT NULL,
`createdAt` datetime NOT NULL,
`updatedAt` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
这意味着字符集已设置为"拉丁1" 我可以通过在其中插入一些数据来知道这一点。
为什么?
我设置字符集 ase UF8 有什么错误吗?
如果有人能帮助我,将不胜感激。
感谢您阅读本文。
这将设置连接的字符集。要更改表上的默认字符集,您可以修改my.cnf
[mysqld]
character-set-server = utf8
collation-server = utf8_general_ci
character_set_server = utf8
collation_server = utf8_general_ci
您还可以指定Model.meta.table_settings
以显式指定给定表的字符集。
class MyModel(Model):
# ... fields, etc ...
class Meta:
database = my_db
table_settings = ['ENGINE=InnoDB', 'DEFAULT CHARSET=utf8']
http://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata
- 表及其列具有指定的字符编码。 (拉丁语1,在你的情况下(
- 客户端具有编码。 这表示重音字母等以 1 字节(对于 latin1(或 2 字节(对于 utf8(等编码的方式。
-
你通过 3 个设置告诉MySQL 客户端编码是什么——
character_set_client character_set_connection character_set_results
这些可能是间接设置自您告诉peewee或pymysql的一件事。 * 发生INSERT
或SELECT
时,客户端编码将动态转换为列的编码。
latin1
对西欧语言来说很好,但对世界其他地区来说是不够的。