How To Connect Python Programs To MariaDB
How To Connect Python Programs To MariaDB
PROGRAMS TO MARIADB
HOME (/) » BLOGS (/BLOG) » ANATOLIYDIMITROV'S BLOG (/BLOG/4907)
F R I , 2 0 1 4 11 1 4 0 8 : 3 0 A N AT O L I Y D I M I T R O V
You can use the popular
programming language Python to
manage data stored in MariaDB.
Here is everything you need to
know about connecting to MariaDB
from Python for retrieving, updating,
and inserting information.
If you want to try out Python integration with MariaDB but you don't have a database to play with, you can
use the popular employees example database (https://launchpad.net/testdb/).
MariaDB provides Python support through the MySQL Python package
(https://pypi.python.org/pypi/MySQLpython), which does not come installed with the default Python
installation on most distros. To add it, use any of the installation packages from the official package page
or your distribution's repository.
Next, establish a database connection with code like mariadb_connection =
mariadb.connect(user='python_user', password='some_pass', database='employees') , where you
assign real values for user, password, and database.
Finally, to start interacting with the database and running queries, you need to instantiate the cursor object
with the code cursor = mariadb_connection.cursor() . So far your initial code should look like this:
#!/usr/bin/python
import mysql.connector as mariadb
mariadb_connection = mariadb.connect(user='python_user', password='some_pass', database='empl
cursor = mariadb_connection.cursor()
RETRIEVING INFORMATION
Once you have the initial code in place you can start working with the data. The first thing you should do
is try to retrieve information from the database. Here is code for a query against the employees database:
cursor.execute("SELECT first_name,last_name FROM employees WHERE first_name=%s", (some_name,)
The result of the query is stored in a list called "cursor." To test the result you can print it with a simple
for loop, but for better formatting use Python's string formatting method:
for first_name, last_name in cursor:
print("First name: {}, Last name: {}").format(first_name,last_name)
INSERTING ROWS
You can insert rows into a table in a way similar to retrieving it by using the cursor.execute method:
cursor.execute("INSERT INTO employees (first_name,last_name) VALUES (%s,%s)", (first_name,
last_name)) . Here you should have already assigned the first_name and last_name variables. By
default AUTOCOMMIT is disabled (https://mariadb.com/blog/everyselectyourpythonprogrammay
acquiremetadatalock), meaning queries are not committed, so no data will be saved until you manually
commit with the connection commit method: mariadb_connection.commit() .
You should commit as soon as you are certain that the data is correct and should be recorded. This
allows you to continue with a new transaction if needed. MariaDB allows you to run multiple concurrent
transaction on the same table without locking it when you use XtraDB (InnoDB) engine.
Just as in SQL, the opposite method to commit is rollback. Thus, if you wish to discard the changes from
the last queries, you can use the rollback() method: mariadb_connection.rollback() .
While inserting rows you may wish to find the ID of the last inserted row when it is automatically
generated, as with autoincrement values. You can acquire this useful information with the insert_id()
method of the connection class: mariadb_connection.insert_id() .
Updating and deleting rows is done similarly to inserting them. The only difference is in the query used.
TRAPPING ERRORS
For any of your SQL actions (querying, updating, deleting, or inserting records) you should try to trap
errors, so you can verify that your actions are being executed as expected and you know about any
problems as they occur. To trap errors, use the Error class:
try:
cursor.execute("some MariaDB query"))
except mariadb.Error as error:
print("Error: {}".format(error))
Once you finish working with the database make sure that you close this connection to avoid keeping
unused connections open and thus wasting resources. You can close the connection with the close()
method: mariadb_connection.close()
This is how easy and straightforward it is to connect your Python code to a MariaDB database. Here is
how a complete script should look like:
#!/usr/bin/python
import mysql.connector as mariadb
mariadb_connection = mariadb.connect(user='python_user', password='some_pass', database='empl
cursor = mariadb_connection.cursor()
#retrieving information
some_name = 'Georgi'
cursor.execute("SELECT first_name,last_name FROM employees WHERE first_name=%s", (some_name,)
for first_name, last_name in cursor:
print("First name: {}, Last name: {}").format(first_name,last_name)
#insert information
try:
cursor.execute("INSERT INTO employees (first_name,last_name) VALUES (%s,%s)", ('Maria','D
except mariadb.Error as error:
print("Error: {}".format(error))
mariadb_connection.commit()
print "The last inserted id was: ", cursor.lastrowid
mariadb_connection.close()
Tags: Developer (/blogtags/developer)
Anatoliy Dimitrov is an open source enthusiast with substantial professional
experience in databases and web/middleware technologies. He is as interested in
technical writing and documentation as in practical work on complex IT projects.
His favourite databases are MariaDB (sometimes MySQL) and PostgreSQL. He is
currently graduating his master's degree in IT and aims to a PhD in Bionformatics
in his home town University of Sofia.
Tweet
39 22 4
Like
FOR COMPATIBILITY (/COMMENT/195#COMMENT-195)
There is a 'friendly fork' of MySQLpython that is more up to date and
adam_johnson_g Python 3 compatible: https://github.com/PyMySQL/mysqlclientpython
Feb 8 2015
(https://github.com/PyMySQL/mysqlclientpython) . Basically just install
`mysqlclient` instead of `MySQLpython`.
Log in (/user/login?destination=node/1672%23commentform) or register
(/user/register?destination=node/1672%23commentform) to post comments
MYSQLCLIENT VS MYSQL.CONNECTOR
josephDB (/COMMENT/236#COMMENT-236)
Jul 15 2015
@adam_johnson_g Is it really true that mysqlclient is more uptodate and
Python 3 compatible?
Having a hard time choosing between the two.
1. mysqlclient has no documentation except for PEP249. Wondering if
rowcount attribute on SELECT requires an extra trip to the database, in
which case it should probably return 1 as per PEP249.
2. for me mysql.connector is running great on Python3.4. I am guessing that
it is closer to MySQL, which is probably what you want in a connector.
==> great documentation
==> it mentions a C version as of 2.1, but don't say when it's coming out
==> has a number of features absent from mysqlclient: you can set more
things in the connection (for instance the collation), you have is_connected,
named_tuple, cursor.statement, cursor.with_rows and many othes.
Log in (/user/login?destination=node/1672%23commentform) or register
(/user/register?destination=node/1672%23commentform) to post comments
Login (/user/login) or register (/user/register) to post comments
Subscribe to get MariaDB tips, tricks and news updates in
your inbox
SUBSCRIBE (/ABOUT/NEWSLETTERSIGNUP)
› Events (/newsevents/events) › MariaDB.org (http://mariadb.org)
› Newsletters (/news
events/newsletters)
› Webinars (/news
events/webinars)