Switch to full style
Python Technology Tutorials Written By Members.
Post a reply

Python Module for MySQL

Sun Jul 22, 2012 4:14 pm

In this article we show you how to start an access to database (MYSQL) using a module named oursql, you can check it here:
Code:

http
://packages.python.org/oursql/
 

Oursql is one of the best modules for MYSQL access. First will need to install it using following command:
Code:
$ pip install oursql

________________________________________
Or you can install it from the source download from the link provided previously. Before we start you much have a MYSQL C clients libraries installed on your system, now lets us move forward for some basics when deal with this package to access MYSQL database, following snippet do some basic operations such as opening a database connection, and running queries :
Code:

import oursql

## connect to database on local machine
conn = oursql.connect(host='localhost', user='root', passwd='root', db='codemiles')

## get the cursor object, by the specifying the cursor class to be used, 
## if left blank defaults will be used
mycurs = conn.cursor(oursql.DictCursor)

## run  query
mycurs.execute("SELECT * FROM User")

## fetching the data( rows)
while (1):
     myrow = mycurs.fetchone()
     ## row empty marks end of resultset
     if row == None:
       break
     
## Print Data
     print "%s" % (myrow['FirstName'])
     print "%s" % (myrow['LastName']) 

With this module you can also use placeholders such as question mark (?) which will be replaced dynamically with any value later on, see this example:
Code:


curs
.execute("SELECT * FROM Department WHERE NumOfSudents>= ? ",(300)

##  fetching results
while (1):
     row = curs.fetchone()
     ## row empty marks end of resultset
     if row == None:
       break
     
## Print Data
     print "%s" % (row['Department_Name'])
 




Post a reply
  Related Posts  to : Python Module for MySQL
 Job Project : Check verification module for NCR registers     -  
 hashing in python     -  
 how to use GeoIP with Python     -  
 Reading email in Python     -  
 How to read and write to CSV file from python     -  
 exception handling try and catch in Python     -  
 usage of SQLite database from Python     -  
 Python Training from Certified Experts (ap2v.com)     -  
 Build Linear Regression in Python - Supervised Learning     -  
 need help in mysql     -  

Topic Tags

Python Database