> For the complete documentation index, see [llms.txt](https://dahye-jeong.gitbook.io/django/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dahye-jeong.gitbook.io/django/basic/2019-03-07-model/2019-03-16-mysql.md).

# MySQL 연동

Django에 mysql을 연동하여 사용해 볼 것이다. [MySQL 시작하기](https://dh00023.gitbooks.io/database/content/MySQL/post/2019-03-16-install.html)에서 설치방법과 기본적인 사용법을 확인할 수 있다.

## MySQL DB API Driver 설치하기

MySQL을 Django와 연동하기 위해서는 `mysqlclient` 가 필요하다.

```
$ pip install mysqlclient
```

```
$ pip list
Package     Version
----------- -----------
Django      2.1.7
mysqlclient 1.4.2.post1
pip         19.0.2
pytz        2018.9
setuptools  40.6.2
```

## settings.py 설정

```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': '', 
        'USER': '', 
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
```

* `NAME`: 생성한 데이터베이스 이름
* `USER`: 데이터 베이스 계정(user)명
* `PASSWORD`: 계정 비밀번호
* `HOST`: 데이터베이스 주소
* `PORT`: 데이터베이스 포트 번호 - MySQL의 경우 3306

이와 같은 정보는 git으로 관리하게 되는 경우 보안상 문제가 발생할 수 있으므로 별도의 파일을 생성해 불러올 것이다.

```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': dev_secrets['DATABASES']['NAME'],
        'USER': dev_secrets['DATABASES']['USER'],
        'PASSWORD': dev_secrets['DATABASES']['PASSWORD']
    }
}
```

```
$ python manage.py migrate
```

migrate후에 mysql에서 설정한 사용자, 데이터베이스에 접속하여 테이블을 확인해보면 다음과 같이 나타난다.

```sql
> show tables;
+----------------------------+
| Tables_in_django           |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| blog_post                  |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
11 rows in set (0.00 sec)
```

## 참고 페이지

* [Multiple databases](https://docs.djangoproject.com/en/2.2/topics/db/multi-db/)
* [django에서 mysql을 사용해보자](https://wkdtjsgur100.github.io/django-mysql-setting/)
