Django如何連接mysql數據庫

(1)安裝MySQLdb類庫
 方法一:下載安裝http://www.djangoproject.com/r/python-mysql/
 方法二:pip安裝  
 sudo pip install mysql-python
 顯示Successfully installed mysql-python-1.2.5
(2)修改settings.py 配置數據屬性

代碼如下:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'mysql',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',                      # Set to empty string for default.
    }
}
修改完後進入項目目錄下執行python manage.py shell命令啓動交互界面輸入一下代碼驗證數據庫配置是否成功。沒報錯則成功!

 代碼如下:

>>> from django.db import connection
>>> cursor = connection.cursor()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章