Python 3: Connect to MySQL with mysql-connector


Here, I will introduce how to connect to MySQL using mysql.connector in Python 3.

Environment Setup

I have tested this on both Ubuntu and Amazon Linux.

Ubuntu

I performed this on Ubuntu 16.04.1 LTS.

To install the necessary packages, run the following command:

Amazon Linux

Assuming Python 3 and its pip package are already installed. The Python version is 3.4.

Download the file from MySQL’s site and install it. I chose “Platform Independent” as the platform, and the downloaded version was 2.1.3. (I couldn’t install it using yum or pip, but there should be a way.)

Copy the downloaded file to the server (you can use scp or similar methods). I moved the copied file to /usr/local/src and extracted it as the root user.

Then, execute the following command as the root user:

Connection Verification

You can verify the connection by running python3 to open the Python console and execute the following command:

If everything goes well, you should see ‘Uptime’ displayed.

Connecting via Code

For example, you can execute a SELECT statement with code like this. Note that it won’t work without the Config class. You can remove the import of Config and directly write connection information. Be cautious of SQL injection possibilities. My Python experience is limited, so the code quality might be low. Sorry about that.