Summary
In this chapter we have looked at where to find MySQL for Python, as it is not part of Python by default. We have also seen how to install it on both Windows and non-Windows systems—UNIX-like and Linux distributions. The authors of MySQL for Python have taken the pain out of this by providing a very easy way to install through an egg utility like EasyInstall
.
Like most modules, MySQL for Python must be imported before you can use it in Python. So we then looked at how to import it. Unlike most modules, we saw that MySQL for Python needs to be imported by its earlier moniker, MySQLdb
.
After that, we took a peek at what is waiting for us under the MySQL for Python covers using help()
. We saw that MySQL for Python is not an interface to MySQL itself but to a MySQL Database API that is built into Python. It has a large number of classes for handling errors, but only one for processing data (There are different kinds of cursors). Further, it does not even use classes to access MySQL, but uses functions to process and pass information to _mysql,
which then passes it to the C MySQL database interface.
Following this trail, we also saw that _mysql
does not have a robust facility for handling errors, but only passes them to the calling process. That is why MySQL for Python has such a robust error handling facility.
Next, we saw how to connect to a MySQL database. As with most parts of Python, this is easy for beginners. But the function used is also sufficiently robust to handle the more complex needs of advanced solutions.
After connecting, we created a MySQLdb
cursor and prepared to interact with the database. This showed that, while there are many things that MySQLdb
will take care of for us (like connection closure), there are some things we need to do manually. In this instance, it is creating the cursor
object that represents the MySQL cursor.
Finally, we saw that one can connect to multiple databases by simply using different object names for each connection. This has the consequence of necessitating different namespaces as we refer to the methods and attributes of each object. But it also allows one to bridge between databases across multiple hosts seamlessly and to present a unified interface for a user.
In the next chapter, we will see how to form a MySQL query and pass it from Python using variables from the system, MySQL, and the user.