![]() |
Access MySQL Databases in Python
Python being one of the most popular languages, it's being used increasingly used for creating dynamic websites or for specific parts of websites, like Google's support fully runs on Python scripts. But, for this type of usage the ability to access RDBMS is indispensable, although unlike PHP, Python does not provide any in-built functions to access the popular relational database system used on the web, it has plenty of stable & feature-rich third party modules which can help accomplish the requirement.
In this article we'll look into the module MySQLdb which allows Python scripts to connect & MySQL databases. Installing MySQLdbMySQLdb requires Python 2.3.4 or higher to work, also it'll work only with MySQL 3.23.32 or higher. Download latest stable release of MySQLdb from http://sourceforge.net/projects/mysql-python/, extract and follow the instructions in the README file, the installation is pretty simple if you have the dependencies in place. If you have to running Debian or Ubuntu, all you need to do is to run the following command as root: Code:
Basic UsageIn basic usage we'll see how to connect to a MySQL database server, execute a SQL & fecthing a record, see the following sample, I've added comments to help understand the important steps. Code: Python
Advanced UsageIn the following code example I would demonstrate advanced usage like error handling, fetching the whole resultset at once, closing statements handles & connection handles. Follow the sample code below: Code: Python
Referenceshttp://mysql-python.sourceforge.net/MySQLdb.html |
| All times are GMT +5.5. The time now is 01:35. |