Tornado – Database MySQL Client Wrapper

Tornado provides a simple MySQL wrapper for performing database operations. Class tornado.databse.Connection acts as a wrapper over MySQLdb DB-API connection.

Consider you have a MySQL installed on your system and you create a DB ‘mydb’ with table ‘post’ and records as below:

mysql> use mydb
Database changed

mysql> create table post (Id int, Title char(50), Author char(50));
Query OK, 0 rows affected (0.03 sec)

mysql> insert into post values (1, 'Tornado Database', 'TechnoBeans');
Query OK, 1 row affected (0.01 sec)

mysql> insert into post values (2, 'Tornado Authentication', 'TechnoBeans');
Query OK, 1 row affected (0.00 sec)

mysql> insert into post values (3, 'Tornado Locale', 'TechnoBeans');
Query OK, 1 row affected (0.00 sec)

mysql> select * from post;
| Id   | Title                  | Author      |
|    1 | Tornado Database       | TechnoBeans |
|    2 | Tornado Authentication | TechnoBeans |
|    3 | Tornado Locale         | TechnoBeans |
3 rows in set (0.02 sec)

Tornado helps you to connect, retrieve and display records from ‘mydb’ MySQL DB as shown in the example below

import tornado.ioloop
import tornado.web
import tornado.database
class Main(tornado.web.RequestHandler):
def get(self):
class DBHandler(tornado.web.RequestHandler):
def get(self):
db = tornado.database.Connection(
host="localhost", database="mydb",
user="root", password="root")
rows = db.query("select Id,Title from post")
top = "<html><body><b>Posts</b><br /><br />"
table = "<table border=\"1\"><col width=\"50\" /><col width=\"200\" />"
for row in rows:
table += "<tr><td>" + str(row["Id"]) + "</td><td>" + str(row["Title"]) + "</td></tr>"
bottom = "</body></html>"
application = tornado.web.Application([
(r"/", Main),
(r"/posts", DBHandler),
if __name__ == "__main__":



In this example:

1. tornado.database.Connection connects to MySQL DB instance with appropriate server, database name, username and passwd

2. Object of class tornado.database.Connection ‘db’ is then used to query the records of table ‘post’

3. DB connection is then closed with db.close()

4. Records are then rendered by the webserver on accessing http://localhost/posts URL


While trying out this example, you may bump into this error

ubuntu@ubuntu:~/tornado-2.2$ python 
Traceback (most recent call last):
  File "", line 4, in 
    import tornado.database
  File "/home/ubuntu/tornado-2.2/tornado/", line 20, in 
    import MySQLdb.constants
ImportError: No module named MySQLdb.constants

This is because python-mysqldb is not installed on your system. On ubuntu systems, you can get it with

sudo apt-get install python-mysqldb

2 thoughts on “Tornado – Database MySQL Client Wrapper

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.