Python Tutorial

Monday, June 20, 2011

Mysql in python: Fetch data

From the code below it's very clear that you need to create a database first named py_sample_db
Then you need to create a table named sample_py_table with two colums (name,email), all contents are varchar type.

You can also run this code on your own database
A sample table:
name email
jonyabu@yahoo.com
jonyzahed@yahoo.com


 '''
  This code use python MySQLdb syntax
 '''

 import MySQLdb
 conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "",db = 
"py_sample_db") cursor = conn.cursor () sql="SELECT * from sample_py_table where name='jony'"; cursor.execute (sql) rows = cursor.fetchall () for row in rows: print "%s, %s" % (row[0], row[1]) cursor.close () conn.close () print "Fetch success"
Output
 
 jony, abu@yahoo.com
jony, zahed@yahoo.com

0 comments:

Post a Comment