python3.6下pycharm連接mysql


 

  由於python3.x里面沒有了MysqlDB,所以使用python3.6+django連接不上mysql,會報錯 no modul "MysqlDB"。於是就有了一個替代品,叫pymysql。

 

1. 安裝pymysql:

1 pip3 install pymysql

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

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 }

 

注意: 

  以上數據庫配置之前需要通過數據庫創建配置里指定的數據庫(注意名稱是否相同)。

 

4. 連接測試

 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數據庫連接成功,並且自動創建表。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM