Python
  Home arrow Python arrow Page 3 - 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 
eWeek
 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
     
     
    Web Buyers Guide
     
    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, Step by Step continued
    (Page 3 of 4 )

      

    3. Execution of the SQL statement

    The steps enumerated until now have done the job of connecting the application with the database and providing an object that simulates the functionality of cursors. The stage has been set for execution of SQL statements. Any SQL statement supported by MySQL can be executed using the execute() method of the Cursor class. The SQL statement is passed as a string to it. Once the statement is executed successfully, the Cursor object will contain the result set of the retrieved values. For example, to retrieve all the rows of a table named USER_MASTER the statement would be:

    cursor.execute(“select * from USER_MASTER”)

    Once the above statement is executed, the cursor object would contain all the retrieved. This brings us to the fourth step, fetching of the resultset. Before moving on to the next step, there is one point you must understand. The execute() function accepts and executes any valid SQL statement, including DDL statements such as delete table, alter table, and so on. In the case of DDL statements, there is no fifth step (i.e. iteration over the results fetched).

    4. Fetching the resultset

    The flexibility of Python comes to the fore in this step also. In the real world, fetching all the rows at once may not be feasible. MySQLdb answers this situation by providing different versions of the fetch() function of Cursor class. The two most commonly used versions are:

    • fetchone(): This fetches one row in the form of a Python tuple. All the data types are mapped to the Python data types except one -- unsigned integer. To avoid any overflow problem, it is mapped to the long. 
    • fetchall(): This fetches all the rows as tuple of tuples. While fetchone() increments the cursor position by one, fetchall() does nothing of that kind. Everything else is similar.

    The subtleties will become clear from the following example. To fetch one row at a time and display the result, the block would be:

    numrows = int(cursor.rowcount) #get the count of total
    rows in the 
    #resultset

    # get and display one row at a time
    for x in range(0,numrows):
            row = cursor.fetchone()
            print row[0], "-->", row[1]

    The above result can be achieved by using fetchall() as shown below:

    result = cursor.fetchall()

    # iterate through resultset
    for record in result:
            print record[0] , "-->", record[1]

     

    The iteration is through the core Python APIs only. As the returned data structure is tuple, no extra API is required.

    That covers all the steps required to access MySQL. What I have discussed up to now is "the approach of tackling a problem of the type database connectivity." However, in real life, reusability plays a more important role than it has in what you have seen so far. Hence in the next section I will be using the steps discussed until now to create a generic class for accessing MySQL.

    More Python Articles
    More By A.P.Rajshekhar


       · 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...

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




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