Following up on my recent studies with Python for system administration, I learned to handle database creation through Python. Database creation and MySQL user management are common tasks as a web hosting provider because many public websites use MySQL. Most web hosting providers already enable the creation of databases through an interface but I'll focus on the implementation of that interface today.

Installing Required Modules

The first requirement is the MySQLdb module. Fortunately, Ubuntu provides the apt-cache utility to search for the MySQLdb package.

$ apt-get search mysqldb
python-mysqldb - A Python interface to MySQL
python-mysqldb-dbg - A Python interface to MySQL (debug extension)

Now that we've found our package, we can install it.

$ sudo apt-get install python-mysqldb

Establishing the Database Connection

It's the same process as in PHP or C and also similar. mysql_connect() and mysql_real_connect() are the functions used to establish the connection for PHP and C respectively. We can assume that Python is similar but with an OOP approach.

#!/usr/bin/python
import MySQLdb as mysql

conn = mysql.connect('localhost', 'root', 'password')
cursor = conn.cursor()

That was as straightforward as PHP and C.

The cursor object processes all statements for the MySQL conection

Database and User Creation Queries

Specifically, we want to execute database and user creation queries for automating our web hosting management. Each time a new new user registers with a web host, they need a MySQL user and possibly a few MySQL databases. For this example, we will assume that one database is assigned per user.

There are three queries necessary:

CREATE DATABASE db;
GRANT ALL ON db.* to user@localhost IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

These queries should be executed in our Python script but the database name, username and password should vary; thus, they will be command line arguments.

#!/usr/bin/python
import MySQLdb as mysql
import sys

# Establish MySQL connection
conn = mysql.connect('localhost', 'root', 'password')
cursor = conn.cursor()

# Execute database and user creation queries
cursor.execute('CREATE DATABASE {database_name};'.format(database_name=sys.argv[0]))
cursor.execute("GRANT ALL ON {database_name}.* TO {username}@localhost IDENTIFIED BY '{password}'".format(database_name=sys.argv[0], username=sys.argv[1], password=sys.argv[2])
cursor.execute('FLUSH PRIVILEGES;')

sys.argv is an array that holds all command line arguments. The execute() method of the cursor object uses the command line arguments as parameters for formatted strings.

All the of the database tasks are complete and you can execute this on the command line.

$ python project.py [database_name] [username] [password]

Notice that the database_name, username and password correspond to the project command line arguments such that we can create databases for new users without entering the MySQL console anytime.

Refactoring for Clean Code

As Python programmers, we should adhere to some programming standards by handling errors and closing our connections.

#!/usr/bin/python
import MySQLdb as mysql
import sys

try:
  # Establish MySQL connection
  conn = mysql.connect('localhost', 'root', 'password')
  cursor = conn.cursor()

  # Execute database and user creation queries
  cursor.execute('CREATE DATABASE {database_name};'.format(database_name=sys.argv[0]))
  cursor.execute("GRANT ALL ON {database_name}.* TO {username}@localhost IDENTIFIED BY '{password}'".format(database_name=sys.argv[0], username=sys.argv[1], password=sys.argv[2])
  cursor.execute('FLUSH PRIVILEGES;')

  # Clean up the connections
  cursor.close()
  conn.close()
except mysql.Error, e:
  print('Error %d: %s' % (e.args[0], e.args[1]))
  sys.exit(1)

This is our final product for creating new MySQL databases and users for web hosts with Python.

Hopefully web host management isn't as tedious now.