Installing MariaDB and connecting it to Python on Fedora Workstation 33
I am writing this simple article to help anyone who struggles to install all the components successfully on Linux due to errors that may occur on the way. I am going to focus on Linux Fedora, but it will be similar on all other distributions as well, just maybe some other package managers come to play.
- Install MariaDB
Required fedora packages (it could be called differently on other distributions):
mariadb, mariadb-server -> contains the Mariadb client and server
mariadb-connector-c-devel -> Contains the connector
su - root # get root access
dnf install mariadb mariadb-server # Install MariaDB stuff
systemctl start mariadb # Start the server as a service
mysql_secure_installation # Install secure components
systemctl enable mariadb # Enable MariaDB service on startup
Source: https://fedoraproject.org/wiki/MariaDB
2. Install the required connector for pip3
We need to install a special connector component that the server requires.
dnf install mariadb-connector-c-devel
Source: https://ask.fedoraproject.org/t/mariadb-python-connector/9151
3. Install Python developer tools
So the last little hassle that I come up with and you might tackle as well is that the installation of pip3 mariadb component will complain that you don’t have a python header file Python.h
. To solve this, you need to install python developer tools like such:
dnf install python3-devel # for python3.x installs
Source: https://stackoverflow.com/questions/21530577/fatal-error-python-h-no-such-file-or-directory
4. Final part: install MariaDB connector on pip3
The pip3 is the Python 3 package manager, and it usually comes out of the box with Python and on Linux distributions. Just install the connector for Python now like such:
pip install mariadb
5. Connecting Python and MariaDB
Connection to MariaDB is well explained on the official documentation, which suggests the following:
# Import MariaDB Connector/Python module
import mariadb# Establish a connection
connection= mariadb.connect(user="myuser", database="test", host="localhost")cursor= connection.cursor()# Create a database table
cursor.execute("DROP TABLE IF EXISTS mytest")
cursor.execute("CREATE TABLE mytest(id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,"
"first_name VARCHAR(100), last_name VARCHAR(100))")# Populate table with some data
cursor.execute("INSERT INTO mytest(first_name, last_name) VALUES (?,?)",
("Robert", "Redford"))# retrieve data
cursor.execute("SELECT id, first_name, last_name FROM mytest")# print content
row= cursor.fetchone()
print(*row, sep='\t')# free resources
cursor.close()
connection.close()
Source: https://mariadb-corporation.github.io/mariadb-connector-python/usage.html
If you need any help setting up MariaDB Database for the first time, please check the following article: https://mariadb.com/get-started-with-mariadb/