Python MySQL

Python can be used in database applications.

MySQL is one of the most popular databases.

MySQL Database

To be able to test the code examples in this tutorial, you should install MySQL on your computer.

Please download the free MySQL database here:https://www.mysql.com/downloads/.

Install MySQL Driver

Python requires the MySQL driver to access the MySQL database.

In this tutorial, we will use the driver "MySQL Connector".

We recommend using PIP to install "MySQL Connector".

PIP is likely already installed in the Python environment.

Navigate to the command line location of PIP, then type the following content:

Download and install "MySQL Connector":

C:\...\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector

Now, you have downloaded and installed the MySQL driver.

Test MySQL Connector

To test whether the installation is successful or if you have installed "MySQL Connector", please create a Python page containing the following content:

demo_mysql_test.py:

import mysql.connector

Run Instance

If there are no errors when executing the above code, then "MySQL Connector" is installed and ready to use.

Create Connection

First, create a connection with the database.

Use the username and password from the MySQL database:

demo_mysql_connection.py:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword"
)
print(mydb)

Run Instance

Now, you can start querying the database using SQL statements.