Chrome Extension

Install MySql and Connect with Python Django

Article Image

MySQL is a relational database that is frequently used to store and query data. In this article, we will learn to install the MySQL database and create a connection with Django

Install Mysql

The easiest way to install MySQL is by using the brew command if you are using Mac for the development. To install MySQL run below command

brew install mysql

This will install MySQL on your system. But it is not running yet. To run MySql use the below command

brew services start mysql

The above command will start MySQL service and you can connect to it without using a password. To connect to MySQL use command from terminal

mysql -u root

If you want to set up a password while connecting to MySQL, you can use the command

mysql_secure_installation

This will start the process of setting the password by following the instructions opened by running the above command. After setting the password you can connect to the MySQL by using below command

mysql -u root -p

After running the above command it will ask you the newly created password. It will create a connection to the MySQL server. Now create a database that we will use in our Django application. You can create a database using the command

CREATE DATABASE Company;

Here Company is the name of the database. Now We are ready to connect it to Django.

Connect Mysql Server with Django

To connect our Django application to MySQL we need to install MySQL driver which can be installed in your project by using the below command.

pip install mysqlclient

Open your settings.py file in Django project and replace database settings with below

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Company',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': 'localhost'
    }
}

 You have now established a connection with MySQL database and you are ready to migrate your models with MySQL database. To create tables run the below command from the Django project

python manage.py makemigrations
python manage.py migrate

This will create tables to the Company database and you can use this in your Django project.

0 Comments
Never leave your website again in search of code snippets by installing our chrome extension.
Open Code Manager We are hiring