Connecting to MariaDB with PyMySQL

PyMySQL is a free and open source project released under the MIT License. PyMySQL is a MySQL library that can be used to interact with the database. You can connect and manage your MySQL database from Python using PyMySQL. PyMySQL supports MySQL/MariaDB version greater than 5.5. PyMySQL is a drop-in replacement for MySQLdb that implements the Python Database API v2.0.

In this tutorial, we will learn how to connect MariaDB with PyMySQL on Ubuntu 18.04 server.

Requirements

A server running Ubuntu 18.04.

A root password is set up on your server

Getting Started

Before starting, it is recommended to update your repository and packages with the latest version. You can do it with the following command:

apt-get update-yapt-get upgrade-y

Once the server is updated, restart it to apply all the changes.

Install Required Packages

First, you will need to install MariaDB server and some required packages in order to install PyMySQL. You can install all of them with the following command:

# connection is not autocommit by default. So you must commit to save# your changes.connection.commit()

withconnection.cursor()as cursor:# Read a single record
sql ="SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql,('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:connection.close()

Save and close the file. Then, run the Python code with the following command:

python sqlenv/connectmysql.py

Once the connection established successfully, you should see the following output:

{u'password': u'very-secret', u'id': 1}

Congratulations! you have successfully install PyMySQL on your server and connect it to the MariaDB database.

About the author

Hitesh Jethva

I am Hitesh Jethva lives in Ahmedabad, INDIA. I am Linux system administrator and Technical writer.

I felt in love with Linux while i was started to learn Linux. I am a fan of open source technology and have more than 8+ years of experience in Linux and Open Source technologies. My main motto is to make uncomplicated things easier.