python3.6下pycharm鏈接mysql

 

  因爲python3.x裏面沒有了MysqlDB,因此使用python3.6+django鏈接不上mysql,會報錯 no modul "MysqlDB"。因而就有了一個替代品,叫pymysql。python

 

1. 安裝pymysql:mysql

1 pip3 install pymysql

2. 把pymysql模塊載入到項目之中(__init__文件里加入):  sql

1 import pymysql
2 pymysql.install_as_MySQLdb()

3. 到settings裏設置數據庫:數據庫

 1 database_host = '192.168.165.129'
 2 database_port = '3306'
 3 database_user = 'root'
 4 database_password = 'abc123'
 5 
 6 DATABASES = {
 7     'default': {
 8         #'ENGINE': 'django.db.backends.sqlite3',
 9         #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
10         'ENGINE': 'django.db.backends.mysql',
11         'NAME': 'cmdb_master',
12         'HOST': database_host,
13         'PORT': database_port,
14         'USER': database_user,
15         'PASSWORD': database_password,
16         'OPTIONS': {
17             'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
18         }
19 
20     }
21 }

 

注意: django

  以上數據庫配置以前須要經過數據庫建立配置裏指定的數據庫(注意名稱是否相同)。python3.x

 

4. 鏈接測試session

 1 python3 manage.py migrate  #運行命令
 2 
 3 System check identified some issues:
 4 Operations to perform:
 5   Apply all migrations: admin, auth, contenttypes, sessions
 6 Running migrations:
 7   Applying contenttypes.0001_initial... OK
 8   Applying auth.0001_initial... OK
 9   Applying admin.0001_initial... OK
10   Applying admin.0002_logentry_remove_auto_add... OK
11   Applying contenttypes.0002_remove_content_type_name... OK
12   Applying auth.0002_alter_permission_name_max_length... OK
13   Applying auth.0003_alter_user_email_max_length... OK
14   Applying auth.0004_alter_user_username_opts... OK
15   Applying auth.0005_alter_user_last_login_null... OK
16   Applying auth.0006_require_contenttypes_0002... OK
17   Applying auth.0007_alter_validators_add_error_messages... OK
18   Applying auth.0008_alter_user_username_max_length... OK
19   Applying sessions.0001_initial... OK

 顯示以上信息說明mysql數據庫鏈接成功,而且自動建立表。ide

相關文章
相關標籤/搜索