Using SQLAlchemy with MariaDB Connector/Python: Part 1 | MariaDB (2024)

Last year we released the new MariaDB Python connector and published a blog post on how to get started using it in your applications. Based on the overwhelmingly positive response that MariaDB Connector/Python has received, we’re going to develop additional tutorials and sample code to help showcase how easy it is for you to use MariaDB Connector/Python within your solutions.

Python is a very powerful and versatile programming language, capable of being used in a large variety of applications, solutions, and integrations. Ultimately, that’s one of the reasons why the Python language has become so popular.

In this blog, we’ll walk through the process for creating a Python application that uses MariaDB Connector/Python and SQLAlchemy to connect to and communicate with a MariaDB database instance.

For those of you that prefer to jump directly into the code you can find all of the source code for this walkthrough here.

Object-Relational Mapping

It goes without saying that creating new applications is a daunting task. Integrating an application with a backing database, like MariaDB, can involve a significant amount of effort to plan and manage interactions like accessing, querying, and persisting data. For some, object-relational mapping (ORM) tools and libraries help to offload boilerplate code for things like data access and object persistence.

In this walkthrough we’ll be focusing on a library called SQLAlchemy, which is a Python SQL toolkit and object relational mapper that gives application developers the full power and flexibility of SQL.

Recently MariaDB engineers submitted pull requests (PR) to the SQLAlchemy repository to add support for the MariaDB dialect. Now that the PR has been accepted and merged, SQLAlchemy v.1.4+ includes support that enables developers to use MariaDB Connector/Python as the underlying driver.

Requirements

Before jumping into code, you’ll need to make sure you have a few things on your machine:

Downloading and Installing

In order to use MariaDB Connector/Python you’ll need to have access to an instance of MariaDB Server. There are a variety of ways you can get started with MariaDB on your local machine, on-premises, or even in the cloud.

  1. Download and install MariaDB Community Server
    1. Directly
    2. Using a Docker image
  2. Download and install MariaDB Enterprise Server
  3. Deploy with MariaDB SkySQL, MariaDB’s database-as-a-service (DBaaS)

Once you’ve downloaded, installed, and gained access to a MariaDB database instance you’ll need to add the company database that we use for the walkthrough.

Using a client of your choice connect to your MariaDB instance and execute the following statement:

CREATE DATABASE company;

Preparing a Python Environment

After establishing access to MariaDB Server, it’s time to create a new Python application. However, before you can do that you’ll need to have all the necessary PyPi packages installed.

To keep things simple you can start by setting up a new virtual environment, which is simply a directory tree that contains Python executable files and other files which indicate that it is a self contained environment.

$ python3 -m venv venv

Before you can start installing or using packages in your virtual environment, you’ll need to activate it. Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell’s PATH.

Activate the virtual environment using the following command:

$ . venv/bin/activate activate

Finally, install the Maria Connector/Python and SQLAlchemy packages from the Python Package Index (PyPi).

$ pip3 install mariadb SQLAlchemy

Connecting to MariaDB Server with Python and SQLAlchemy

Now that a Python virtual environment has been set up, and the necessary packages have been installed, you’re ready to start creating a new application. For this tutorial, and the sake of simplicity, we’ll keep everything within a single file called tasks.py.

Start by creating a new Python file.

$ touch api.py

Next, using a code editor of your choice, open api.py and add the following import statements.

import sqlalchemyfrom sqlalchemy.ext.declarative import declarative_base

To connect to MariaDB using SQLAlchemy you’ll need to create a new engine, which uses database connection configuration information to connect to and communicate with an underlying database.

# Define the MariaDB engine using MariaDB Connector/Pythonengine = sqlalchemy.create_engine("mariadb+mariadbconnector://app_user:Password123!@127.0.0.1:3306/company")

In the preceding engine declaration, the following connection configuration information is indicated:

  • User*: app_user
  • Password*: Password123!
  • Host: 127.0.0.1 (localhost)
  • Port: 3306
  • Default database: company

* This walkthrough assumes certain credentials, but can be configured to your specific test environment.

For more information on the SQLAlchemy engine capabilities please refer to the official documentation.

Mapping to data

SQLAlchemy features two styles of being able to configure mappings between Python classes and a database table. The “Classical” style is SQLAlchemy’s original mapping API, whereas “Declarative” is the richer and more succinct system that builds on top of “Classical”. It’s important to note that both styles can be used interchangeably, as the end result of each is exactly the same, but for the purposes of this walkthrough you’ll be implementing the “Declarative” approach.

In a declarative mapping configuration the components of the user-defined class as well as the database table metadata to which the class is mapped are defined at once.

Base = declarative_base()class Employee(Base): __tablename__ = 'employees' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) first_name = sqlalchemy.Column(sqlalchemy.String(length=100)) last_name = sqlalchemy.Column(sqlalchemy.String(length=100)) active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)

One of the neat things about many object-relational mapping libraries is that they give you the ability to create database entities, like tables, using the mapped class. In SQLAlchemy you can do so by calling the create_all method.

Base.metadata.create_all(engine)

Working with data

Creating new session

To start communicating with a MariaDB database you’ll first need to create a new Session object using SQLAlchemy’s sessionmaker functionality.

Session = sqlalchemy.orm.sessionmaker()Session.configure(bind=engine)Session = Session()

Inserting data

Adding a new employee to the employees table is done by creating a new Employee object, adding it to the existing SQLAlchemy session, and then committing the session.

newEmployee = Employee(firstname=”Rob”, lastname=”Hedgpeth”)session.add(newEmployee)session.commit()

Selecting data

Once you’ve gotten data into your employees table you can select it by using the query() method that’s available on the Session object.

You can use a Query object, which is returned by the query() method to return the entire set of data that exists in your table

employees = session.query(Employee).all()

You can specify a particular record based the primary key

employee = session.query(Employee).get(1)

Or even use the filter_on() method to target specific characteristics of a mapped object

employee = session.query(Employee).filter_on(firstname=”Rob”)

And a heck of a lot more as well.

For more information on the Query object capabilities be sure to check out the official SQLAlchemy documentation.

Updating data

A simple way to update a table record by first selecting a mapped object, using the previously mentioned Query object.

employee = session.query(Employee).get(1)

Then you can modify the mapped properties, and commit the session to update the database record.

employee.firstname = “Robert”session.commit()

Deleting data

Deleting mapped objects is as easy as specifying the records you want to delete, through the use of the filter() method, and then calling the delete(). Then simply commit the transaction by calling the commit() method on the Session object.

session.query(Employee).filter(Employee.id == id).delete()session.commit()

Putting it all together

The following code snippet brings everything together in one concise example. To test it out just copy and paste the code block into your employee.py file. You can also find the code here.

The Full Source

import sqlalchemyfrom sqlalchemy.ext.declarative import declarative_base# Define the MariaDB engine using MariaDB Connector/Pythonengine = sqlalchemy.create_engine("mariadb+mariadbconnector://app_user:Password123!@127.0.0.1:3306/company")Base = declarative_base()class Employee(Base): __tablename__ = 'employees' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) firstname = sqlalchemy.Column(sqlalchemy.String(length=100)) lastname = sqlalchemy.Column(sqlalchemy.String(length=100)) active = sqlalchemy.Column(sqlalchemy.Boolean, default=True)Base.metadata.create_all(engine)# Create a sessionSession = sqlalchemy.orm.sessionmaker()Session.configure(bind=engine)session = Session()def addEmployee(firstName,lastName): newEmployee = Employee(firstname=firstName, lastname=lastName) session.add(newEmployee) session.commit()def selectAll(): employees = session.query(Employee).all() for employee in employees: print(" - " + employee.firstname + ' ' + employee.lastname)def selectByStatus(isActive): employees = session.query(Employee).filter_by(active=isActive) for employee in employees: print(" - " + employee.firstname + ' ' + employee.lastname)def updateEmployeeStatus(id, isActive): employee = session.query(Employee).get(id) employee.active = isActive session.commit()def deleteEmployee(id): session.query(Employee).filter(Employee.id == id).delete() session.commit()# Add some new employeesaddEmployee("Bruce", "Wayne")addEmployee("Diana", "Prince")addEmployee("Clark", "Kent")# Show all employeesprint('All Employees')selectAll()print("----------------")# Update employee statusupdateEmployeeStatus(2,False)# Show active employeesprint('Active Employees')selectByStatus(True)print("----------------")# Delete employeedeleteEmployee(1)# Show all employeesprint('All Employees')selectAll()print("----------------")

Run the application

To execute the code in employees.py just open a terminal window, navigate to the location of your employees.py file and execute the following:

$ python3 employees.py

The Tip of the Iceberg

Hopefully this walkthrough has helped you take your first steps into the wonderful world of creating applications with MariaDB Connector/Python and SQLAlchemy.

While it’s crucial to get a basic understanding of SQLAlchemy we’ve really only scratched the surface of what it’s capable of. In the second part of this tutorial, we dive into how you can create and manage object relationships using SQLAlchemy.

Using SQLAlchemy with MariaDB Connector/Python: Part 1 | MariaDB (2024)

FAQs

Does SQLAlchemy work with MariaDB? ›

SQLAlchemy supports MySQL starting with version 5.0. 2 through modern releases, as well as all modern versions of MariaDB.

How do I connect to SQLAlchemy in MySQL? ›

Finally, you have the hostname or IP address of the database and the database name. These data are all you need to establish a connection. The port is optional, but SQLAlchemy is smart enough to know the MySQL database resides at port 3306. Finally, you create the connection object and invoke the connect method.

How does SQLAlchemy connect to database in Python? ›

Connecting to SQL Database using SQLAlchemy in Python
  1. Step 1: Importing libraries. import pyodbc. ...
  2. Step 2: Establishing connection to the database. # in order to connect, we need server name, database name we want to connect to. ...
  3. Step 3: Extracting table names present in the database. ...
  4. Step 4: Extracting table contents.
Sep 8, 2019

How do I install MariaDB connector? ›

To configure the CS package repository:
  1. Install wget . Install via APT on Debian, Ubuntu: $ sudo apt install wget. ...
  2. Configure the CS package repository using the mariadb_repo_setup utility: $ sudo ./mariadb_repo_setup \ --mariadb-server-version="mariadb-10.6" ...
  3. Install MariaDB Connector/C using the package repository.

What is the default port for MariaDB? ›

The default port for MariaDB is 3306.

What is MariaDB vs MySQL? ›

MariaDB and MySQL both implement standard SQL syntax, including common table expressions and window functions as well as JSON and geospatial functions. However, MariaDB adds the INTERSECT and EXCEPT set operators, linear regression functions and more.

Is SQLAlchemy the same as MySQL? ›

SQLAlchemy provides a nice “Pythonic” way of interacting with databases. So rather than dealing with the differences between specific dialects of traditional SQL such as MySQL or PostgreSQL or Oracle, you can leverage the Pythonic framework of SQLAlchemy to streamline your workflow and more efficiently query your data.

Is SQLAlchemy a database? ›

It's not a database, but a library for handling databases, or as they put it: SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. The file based dialect is SQLite.

What is MariaDB server? ›

MariaDB is an open source relational database management system (DBMS) that is a compatible drop-in replacement for the widely used MySQL database technology.

Can I use mysql JDBC driver for MariaDB? ›

Yes, MySQL's Connector/J is compatible with MariaDB.

How do I start MariaDB in terminal? ›

Start the MariaDB shell
  1. At the command prompt, run the following command to launch the shell and enter it as the root user: /usr/bin/mysql -u root -p.
  2. When you're prompted for a password, enter the one that you set at installation, or if you haven't set one, press Enter to submit no password.
Mar 22, 2018

Is MariaDB portable? ›

Download MariaDB portable

You must go to https://downloads.mariadb.org/ and select the last version for downloading (or the one you need). In my case, the last version of June 2020 is 10.4. 13. You need to access to View All MariaDB Releases, because the version I need to download it is not the direct link.

How do I create a database connection in SQLAlchemy? ›

import sqlalchemy engine = sqlalchemy. create_engine('mysql://user:password@server') # connect to server engine. execute("CREATE DATABASE dbname") #create db engine. execute("USE dbname") # select new db # use the new db # continue with your work...

What databases does SQLAlchemy support? ›

Supported Databases. SQLAlchemy includes dialects for SQLite, Postgresql, MySQL, Oracle, MS-SQL, Firebird, Sybase and others, most of which support multiple DBAPIs. Other dialects are published as external projects.

What is the difference between PyODBC and SQLAlchemy? ›

PyODBC allows you connecting to and using an ODBC database using the standard DB API 2.0. SQL Alchemy is a toolkit that resides one level higher than that and provides a variety of features: Object-relational mapping (ORM) Query constructions.

How do I connect to a MariaDB database? ›

Windows
  1. Open the command prompt by following this steps: Start -> run -> cmd -> press enter.
  2. Navigate to your MariaDb installation folder (Default: C:\Program Files\MariaDb\MariaDb Server 12\bin)
  3. Type in: mysql -u root -p.
  4. GRANT ALL PRIVILEGES ON *. ...
  5. Run this last command: FLUSH PRIVILEGES;
  6. To exit type: quit.

How do I find my MariaDB port? ›

In order to verify if the port configuration for MySQL/MariaDB database server has been successfully applied, issue netstat or ss command and filter the results via grep command in order to easily identify the new MySQL port.

How do I access my MariaDB remotely? ›

How to enable Remote access to your MariaDB/MySQL database on Ubuntu Bionic or MariaDB < v10. 6
  1. Enabling Remote Access in the Webdock Dashboard. ...
  2. Manual configuration using the command line. ...
  3. Verify MariaDB Server. ...
  4. Configure MariaDB. ...
  5. Grant Access to a User from a Remote System. ...
  6. Configure Firewall.
Feb 2, 2022

What are the limitations of MariaDB? ›

Limitations on Size

MariaDB imposes a row-size limit of 65,535 bytes for the combined sizes of all columns. If the table contains BLOB or TEXT columns, these only count for 9 - 12 bytes in this calculation, given that their content is stored separately. 32-bit operating systems have a maximum file size limit of 2GB.

Can MariaDB replace MySQL? ›

Since MariaDB works as a straight swap for MySQL, you should have no trouble uninstalling MySQL, installing MariaDB in its place, then connecting (so long as the file versions are the same).

What is MariaDB good for? ›

MariaDB Platform offers a columnar database solution that is designed to better support real-time analytics at a large scale. This cloud-native solution combines massively parallel processing with distributed data to give your organization more power and flexibility in what you can do with your data.

Should I use SQLAlchemy core or ORM? ›

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

What are the major benefits of using SQLAlchemy? ›

SQLAlchemy is great because it provides a good connection / pooling infrastructure; a good Pythonic query building infrastructure; and then a good ORM infrastructure that is capable of complex queries and mappings (as well as some pretty stone-simple ones).

Can SQLAlchemy create tables? ›

Let us now discuss how to use the create table function. The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject.

Is ORM faster than SQL? ›

There is little research on which technique is faster. Intuitively, Raw SQL should be faster than Eloquent ORM, but exactly how much faster needs to be researched. In particular, when one uses Raw SQL over Eloquent ORM, one makes a trade-off between ease of development, and performance.

Is SQLAlchemy fast? ›

SQLAlchemy is very, very fast. It's just that users tend to be unaware of just how much functionality is being delivered, and confuse an ORM result set with that of a raw database cursor.

What companies use SQLAlchemy? ›

90 companies reportedly use SQLAlchemy in their tech stacks, including yogiyo, Hivestack, and Buzzvil.
  • yogiyo.
  • Hivestack.
  • Buzzvil.
  • Kaidee.
  • Benchling.
  • Infogrid.
  • FreshBooks.
  • FASTFIVE Digital ...

Is MariaDB free to use? ›

Internal usage is free

Connecting to a remote service that runs MariaDB (or any other GPL software) in the background is also free. For internal programs for which you own all the copyright(s), there is essentially no risk in using GPL software.

Why is it called MariaDB? ›

MariaDB continues this tradition by being named after his younger daughter, Maria. The name Maria was initially given to a storage engine. After MariaDB was started, to avoid confusion, it was renamed to Aria. The new name was decided as a result of a contest.

Who uses MariaDB? ›

MariaDB is used at ServiceNow, DBS Bank, Google, Mozilla, and, since 2013, the Wikimedia Foundation. Several Linux distributions and BSD operating systems include MariaDB.

How do I create a SQLAlchemy database? ›

By passing the database which is not present, to the engine then sqlalchemy automatically creates a new database.
  1. Updating data in Databases. db.update(table_name).values(attribute = new_value).where(condition)
  2. Delete Table. db.delete(table_name).where(condition)
  3. Dropping a Table.
Aug 23, 2018

What is MariaDB server? ›

MariaDB is an open source relational database management system (DBMS) that is a compatible drop-in replacement for the widely used MySQL database technology.

What is SQLAlchemy ORM? ›

SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the times, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.

How do I create a new user in MariaDB? ›

To create a new MariaDB user, type the following command: CREATE USER 'user1'@localhost IDENTIFIED BY 'password1'; In this case, we use the 'localhost' host-name and not the server's IP. This practice is commonplace if you plan to SSH in to your server, or when using the local client to connect to a local MySQL server.

Why should I use SQLAlchemy? ›

The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started. This is why almost all the programming tutorials and courses online teach the high-level approach.

What databases does SQLAlchemy support? ›

Supported Databases. SQLAlchemy includes dialects for SQLite, Postgresql, MySQL, Oracle, MS-SQL, Firebird, Sybase and others, most of which support multiple DBAPIs. Other dialects are published as external projects.

Can SQLAlchemy create tables? ›

Let us now discuss how to use the create table function. The SQL Expression Language constructs its expressions against table columns. SQLAlchemy Column object represents a column in a database table which is in turn represented by a Tableobject.

What are the limitations of MariaDB? ›

Limitations on Size

MariaDB imposes a row-size limit of 65,535 bytes for the combined sizes of all columns. If the table contains BLOB or TEXT columns, these only count for 9 - 12 bytes in this calculation, given that their content is stored separately. 32-bit operating systems have a maximum file size limit of 2GB.

What are the advantages of MariaDB? ›

2019 Update: Open Source Comparisons Released

First and foremost, MariaDB offers more and better storage engines. NoSQL support, provided by Cassandra, allows you to run SQL and NoSQL in a single database system. MariaDB also supports TokuDB, which can handle big data for large organizations and corporate users.

Is MariaDB replace MySQL? ›

Since MariaDB works as a straight swap for MySQL, you should have no trouble uninstalling MySQL, installing MariaDB in its place, then connecting (so long as the file versions are the same). Please be aware that you should run mysql_upgrade to conclude the upgrade process. Replication with MySQL is asynchronous.

Is ORM faster than SQL? ›

There is little research on which technique is faster. Intuitively, Raw SQL should be faster than Eloquent ORM, but exactly how much faster needs to be researched. In particular, when one uses Raw SQL over Eloquent ORM, one makes a trade-off between ease of development, and performance.

Should I use SQLAlchemy core or ORM? ›

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.

Is SQLAlchemy similar to SQL? ›

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.

Top Articles
Latest Posts
Article information

Author: Duncan Muller

Last Updated:

Views: 6042

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duncan Muller

Birthday: 1997-01-13

Address: Apt. 505 914 Phillip Crossroad, O'Konborough, NV 62411

Phone: +8555305800947

Job: Construction Agent

Hobby: Shopping, Table tennis, Snowboarding, Rafting, Motor sports, Homebrewing, Taxidermy

Introduction: My name is Duncan Muller, I am a enchanting, good, gentle, modern, tasty, nice, elegant person who loves writing and wants to share my knowledge and understanding with you.