Python
  Home arrow Python arrow Page 4 - Database Programming in Python: Access...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PYTHON

Database Programming in Python: Accessing MySQL
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 20
    2006-02-21

    Table of Contents:
  • Database Programming in Python: Accessing MySQL
  • Accessing MySQL, Step By Step
  • Accessing MySQL, Step by Step continued
  • Accessing MySQL in the Real World

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    CIO Insight
     
    ADVERTISEMENT

    TestComplete™ automates software testing for a fraction of what the big guys charge. Easy functional and load testing for all Windows, .NET, Java and Web apps. Download a free trial now.

    Database Programming in Python: Accessing MySQL - Accessing MySQL in the Real World
    (Page 4 of 4 )

    Reusability has become the mantra of the current software development paradigm. So this discussion wouldn’t be complete without implementing reusability for database access. The problem is simple; we need to create a generic class that provides the various data manipulation functionalities. I will be developing retrieve and delete functionalities. I am leaving error handling and other functionalities as an ‘experiment’. So let's begin.

    The first step is the required imports and the class name:

    import MySQLdb
    class GenericDBOP:
                :
                :

    Next comes the constructor. It takes two parameters, the database connection and the table name:

    import MySQLdb
    class GenericDBOP:
             
    def __init__(self, db, name):
                self.db = db #database connection
                self.name = name #table name
                self.dbc = self.db.cursor() #cursor object
                 :
                 :

    The connection is established and the cursor object is retrieved. Executing the SQL statement is what has to be done next:

    import MySQLdb
    class GenericDBOP:
              def __init__(self, db, name):
                        self.db = db #database connection
                        self.name = name #table name
                        self.dbc = self.db.cursor() #cursor
    object                  

              def __getitem__(self, item):
                   self.dbc.execute("select * from %s limit %
    s, 1" %
     
                                   (self.name, item))
                   return self.dbc.fetchone()
                        
                         :
                         :

    Here by encapsulating the retrieval functionality in the special function __getitem__ , the class has been provided the ability to access the database as python lists. Although the __getitem__ is good, it executes select query. To make the class more generic, let's add one more function that takes the query to be executed as a parameter:

    import MySQLdb
    class GenericDBOP:
              def __init__(self, db, name):
                        self.db = db #database connection
                        self.name = name #table name
                        self.dbc = self.db.cursor() #cursor object
                         self.debug=1                  

              def __getitem__(self, item):
                   self.dbc.execute("select * from %s limit %s, 1" %
                                   (self.name, item))
                   return self.dbc.fetchone()

              def _query(self, q):
                      if self.debug: print "Query: %s" % (q)
                      self.dbc.execute(q)

                    :
                    :

    Execution is done, but what if there is a requirement to see the statement? In that case, a debug variable is added to the class. This variable can have more utility in the future if the class needs to be more verbose in its output and logging. If the executed query is for retrieval (in other words, a select statement), then a function to fetch the result is required. An iterator pattern would be better in this case. So let's add an iterator and a function that uses the iterator to return the value one by one:

    class GenericDBOP:
              def __init__(self, db, name):
                        self.db = db #database connection
                        self.name = name #table name
                        self.dbc = self.db.cursor() #cursor object
                         self.debug=1                  

              def __getitem__(self, item):
                   self.dbc.execute("select * from %s limit %s, 1" % 
                                          (self.name, item))
                   return self.dbc.fetchone()

              def _query(self, q):
                    if self.debug: print "Query: %s" % (q)
                    self.dbc.execute(q)

              def __iter__(self):
                "creates a data set, and returns an iterator (self)"
                            q = "select * from %s" % (self.name)
                            self._query(q)
                             return self  # an Iterator is an object 
                                                    # with a next() method

    def next(self):
                            "returns the next item in the data set, 
                            or tells Python to stop"
                            r = self.dbc.fetchone()
                            if not r:# Ok here error is handled and rethrown
                                        raise StopIteration
                       return r

    That completes the class. So now it's time to test it. Here it goes:

    if __name__==’__main__’:
            
    db = MySQLdb.connect(user="user", passwd="passwd", 
                        db="library")
            
    books = GenericDBOP (db, "book")

            
    for i in xrange(80, 100):
                        print "Book %s: %s" % (i, books[i])

    Since the __getitem__() has been implemented in the class, we can access the database as python lists. Other functionalities can also be tested in the same way. That brings us to the end of this tutorial/discussion. From this discussion it is obvious that accessing databases from Python is really simple. This time the center of attention was MySQL. However, in the world of relational databases there are other big players and Oracle is one of them. I will be discussing them in future. Till next time.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · HiThanks for reading my article. Hope it has been helpful. If you have any topics...
       · nice tutorial. I'd love to see one on postgresql, as I plan to be using it in the...
       · Thank you for your encouragement. As for pgsql you can use pgdb from...
       · I would make the criticism that it was probably too hard to follow if you haven't...
       · Thank you for your commnets. But I would like to clarify certain things. Firstly the...
       · We would like to see more articles about SQL type programming in Python.Thanks a...
       · Would love to see any article that helps beginner (but already with enough...
       · The link is not available anymore ? I mean, the full article.
       · HiThe link is still there. You can access it from the following link...
     

       

    PYTHON ARTICLES

    - SSH with Twisted
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along
    - Python Operators
    - Bluetooth Programming in Python: Network Pro...
    - Python Sets
    - Python Conditionals, Lists, Dictionaries, an...
    - Python: Input and Variables
    - Introduction to Python Programming
    - Mobile Programming in Python using PyS60: Ge...
    - Bluetooth Programming using Python
    - Finishing the PyMailGUI Client: User Help To...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway