MySQL is a common open source relational database for creating, reading, updating and deleting data in Python web applications. Let’s learn how to install MySQL on Ubuntu 16 and then run a few SQL queries within the command line client.
We will not go over connecting via Python applications using object-relational mappers (ORMs) but these steps can be used as a prerequisite to working with an ORM such as SQLAlchemy or Peewee.
To install MySQL, first set apt-get to query the most up to date list of repositories by running an apt-get update.
We will install 3 packages: mysql-server, libmysqlclient-dev, python-mysqldb. Mysql-server is the main MySQL package, libmysqlclient-dev is the MySQL development library and python-mysqldb is the python interface for MySQL. While the mysql-server package is essential, the others are optional and listed there as they may be useful for most usage. The command is as follow:
apt-get install mysql-server libmysqlclient-dev python-mysqldb
During package installation, you will have a prompt asking you for a new root password. You will need that password when login in to MySQL as the super user.
Once the installation process is finished, you may want to secure your MySQL, especially when used in production. To do that, there is a script called mysql_secure_installation which you can call from the command line, no other utilities necessary.
The script will ask several questions. The root password would not need to be changed. However, it is recommended to remove anonymous users, disallow remote login if you are not going to query the server remotely, remove the test database and reload the privilege on tables.
Once that’s finished, you can now login to mysql in command line. To do so, use the following command:
mysql -u root -p
Enter your password and you will now be logged into the MySQL command line client.