PEP 249規定了Python的數據庫API。MySQL主要有三種API實現:
- MySQLdb 是Andy Dustman開發的、使用原生代碼/C語言綁定的驅動,它已經開發了數十年。
- mysqlclient 是MySQLdb的一個支持Python3的fork,並且可以無縫替換調MySQLdb。mysqlclient目前是MySQL在Django下的推薦選擇。
- MySQL Connector/Python 是Oracle寫的,純Python實現的客戶端庫。
以上所有的驅動都是線程安全的,且提供了連接池。MySQLdb
是唯一一個不支持Python3的。
如果你使用mysqlclient
settings.py中的配置如下:
1 # Database 2 # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 3 4 DATABASES = { 5 'default': { 6 'ENGINE': 'django.db.backends.mysql', #數據庫引擎 7 'NAME': 'test', #數據庫名 8 'USER': 'root', #用戶名 9 'PASSWORD': 'root', #密碼 10 'HOST': '', #數據庫主機,默認為localhost 11 'PORT': '', #數據庫端口,MySQL默認為3306 12 'OPTIONS': { 13 'autocommit': True, 14 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 15 }, 16 } 17 }
第14行主要是為了防止警告:
(mysql.W002) MySQL Strict Mode is not set for database connection 'default'
然后運行migrate :
1 Operations to perform: 2 Apply all migrations: admin, auth, contenttypes, sessions, users 3 Running migrations: 4 Applying contenttypes.0001_initial... OK 5 Applying contenttypes.0002_remove_content_type_name... OK 6 Applying auth.0001_initial... OK 7 Applying auth.0002_alter_permission_name_max_length... OK 8 Applying auth.0003_alter_user_email_max_length... OK 9 Applying auth.0004_alter_user_username_opts... OK 10 Applying auth.0005_alter_user_last_login_null... OK 11 。。。