最近在研究Django抒抬,在鏈接數(shù)據(jù)庫的時候出現(xiàn)了一些小問題杨刨,記錄在此,給自己做個記錄擦剑,同時給各位一個參考妖胀。
首先說明下,在mac電腦上惠勒,用的virtualenv虛擬環(huán)境赚抡,Django的版本是1.11.3,Python的版本是3.6
問題1:
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
問題2:
django.db.utils.OperationalError: (1045, "Access denied for user 'test'@'localhost' (using password: YES)")
出現(xiàn)此問題纠屋,網(wǎng)上有一堆詳解這個問題的原因涂臣,具體可以自己搜索。
我的解決辦法是:
1.先安裝mysql數(shù)據(jù)庫售担,直接brew安裝就行:
brew install mysql
2.啟動mysql服務(wù):
mysql.server start
關(guān)于怎么設(shè)置初始化配置root賬戶參考:
https://segmentfault.com/q/1010000000475470
3.設(shè)置setting.py中的DATABASES:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 或者使用 mysql.connector.django
'NAME': 'TestModel',
'USER': 'test',
'PASSWORD': 'test123',
'HOST': 'localhost',
'PORT': '3306',
}
}
我這里設(shè)置的數(shù)據(jù)庫名字:TestModel赁遗,用戶:test ,密碼:test123
4.同時設(shè)置數(shù)據(jù)庫的相關(guān)參數(shù)與setting.py保持一致族铆,具體如下:
進(jìn)入數(shù)據(jù)庫:
mysql -uroot -p
創(chuàng)建數(shù)據(jù)庫 TestModel的參數(shù)
mysql> create database TestModel;
mysql> create user test idenfified by 'test123';
mysql> grant all on TestModel.* to 'test'@'%';
mysql> flush privileges;
5.最后虛擬環(huán)境中同步一下:
python3 manage.py migrate
python3 manage.py runserver
出現(xiàn)如下:
System check identified no issues (0 silenced).
July 19, 2017 - 01:53:41
Django version 1.11.3, using settings 'MySetting.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
以上就是我解決上兩個問題的思路岩四。
參考鏈接:https://stackoverflow.com/questions/2443419/django-mysql-1045-access-denied-for-user