Python read data from MySQL database

The following code can read data from MySQL database.

import MySQLdb
 
# Open database connection
db = MySQLdb.connect("localhost","username","password","DBName")
 
# prepare a cursor object using cursor  method
cursor = db.cursor() 
 
sql = "select * from table1"
cursor.execute(sql)
results = cursor.fetchall() 
for row in results:
    print row[0]
 
# disconnect from server
db.close()
Category >> Python  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>