How to solve the magic commands problem in Python connecting to MySQL

Photo by Javardh on Unsplash

I have run the magic commands in Python to connect MySQL with the following format:

%load_ext sql
%sql mysql://root:password@localhost/database

It showed the following error info.

In my case, I solved it as the following process:

  1. Check whether SQLAlchemy being installed. Using the below code:
import sqlalchemy
sqlalchemy.__version__ # doctest: +SKIP

In my case, it is 1.3.13.

2. But if it isnโ€™t installed in your case, install it using the below code:

!pip install SQLAlchemy

3. Run the magic command again, the error is the same. Check my Python version

from platform import python_versionprint(python_version())

In my case, it is 3.7.6

4. It seems that for Python 3, module pymysql is needed to run magic command, then install it

!pip install pymysql

5. Run the magic command again, the same error here. Check it again, it seems that instead of using: mysql, the magic command should use module name: mysql+pymysql

%sql mysql+pymysql://root:password@localhost/database

Now the problem is solved.

The check sequeence is: Module SQLAlchemy -> Python version -> Module pymysql -> magic command (mysql+pymysql).

Please keep in mind that this case is for python 3 and I didnโ€™t check other possibilities. It is possible that there are other possibilities in a specific situation.