Connecting to a MySQL database using Python 3 #compsci #SQA #AHcomputingscience

Image by Gerd Altmann from Pixabay

Students completing the SQA Advanced Higher Computing Science course need to create their projects with a major and minor in mind. The major – the main area of content their project will showcase – can be either Software Development (e.g. Python), Web Design and Development (PHP) or Database Design and Development (e.g. MySQL). The minor is another one of the three options but showcasing more basic skills. The major and minor elements have to integrate and this has been causing me a little bit of grief over the past four weeks.

Connecting Python and MySQL should be extremely straightforward: ensure the mysql.connector library is installed on the client and add an import line to your Python program. Unfortunately this message stubbornly refused to leave:

I thought I knew what to do. The first step was to get our IT support team to install the package. This took a while because… bureaucracy. Eventually, just yesterday, it was installed. However the error message above continued to display.

I attempted the steps from home to see if I could work it out. Sometimes it’s easier to solve issues when you try the same steps on a different (off network) computer.

I’ve included the steps below to help any other Computing Science teachers or students who want to set this up too.

1. From terminal / cmd prompt type:

sudo pip install mysql-connector

(The install was successful)

2. Open Python 3.7 (IDLE) and from the shell type:

import mysql.connector

(Error message displayed)

3. From terminal open Python 2.7 by typing:

python

4. Then type:

import mysql.connector

(This was successful)

Image by nugroho dwi hartawan from Pixabay

So I’ve worked out/remembered that pip by default installs the library to the Python 2.7 path. Now what?

The problem was with the pip install line. To force it to install to the Python 3 path I needed to type:

python3 -m pip install mysql-connector

Now when I import the mysql.connector library in Python 3 IDLE it works.

Former students may recognise this scenario!

On Monday I plan to discuss this with IT support so that they can correct the installation and my students can continue with their projects!