Ruddra.com

Install MySQL and MySQLClient (Python) in MacOS

Install MySQL and MySQLClient (Python) in MacOS

Connecting to MySQL from Python in MacOS is a very problematic and painful process. In this post, we are going to see how to install MySQL and connect a Python application to it using mysqlclient.

Step one: install Homebrew

You need to install Homebrew in you local machine. You can do it by:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Step two: install MySQL

Using Homebrew you can install mysql simply by:

brew install mysql

Then setup the credentials in MySQL server using the following command:

mysql_secure_installation

Finally if you want to start at login and as a background service, run this:

brew services start mysql

Else

mysql.server start

Step three: install MySQL-Connector-C

For connecting any other application to MySQL, you need to install a connector. You can do it like this:

brew install mysql-connector-c

Step four: install XCode-Select

You can do this by:

xcode-select --install

Step five: install OpenSSL

Please run the following command:

brew install openssl

Then add its path to environment using following line:

export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/

You need to unlink mysql and link mysql-connector-c:

brew unlink mysql
brew link --overwrite mysql-connector-c --force

Step seven: install mysqlclient

You should be able to use pip install mysqlclient without any errors.

Now, you need to do the opposite of Step six:

brew unlink mysql-connector-c
brew link --overwrite mysql

Hopefully now mysqlclient should work fine and will have no problem connecting your application from mysql to python.

Step nine: add mysqlclient in virtual env(optional)

if you have mysqlclient installed in the system, then you can use --system-site-packages when creating virtual environment:

python3 -m venv venv_name --system-site-packages

Or

virtualenv venv_name --system-site-packages

But, if you do not want to include all the system packages, and you still face error installing mysqlclient in virtual environment, then try following steps:

source venv/bin/activate
brew unlink mysql
brew link --overwrite mysql-connector-c
pip install mysqlclient
brew unlink mysql-connector-c
brew link --overwrite mysql

In conclusion

In this article, we have seen installing MySQL from Homebrew. I never used MySQL installed from Oracle website, so don’t know how to fix it. Better if you uninstall that and install MySQL from scratch using Homebrew.

Last updated: Apr 05, 2024


← Previous
Create Proxy Object in Python

Lets say you have been using a class named ClassA, objects created from that class has been used in …

Next →
Deploy Django App in Sub Directory Using OpenShift

Deploy your Django application in sub directory ie at path '/your-path' using OpenShift

Share Your Thoughts
M↓ Markdown