Wednesday, June 24, 2009

python - basic database connection example with MySQLdb

 
# basic python connect to a mysql database 
import MySQLdb
 
# connect to db 
dbconnection = MySQLdb.connect(host="localhost", user="dbuser", passwd="dbpass", db="mydb")
dbcursor = dbconnection.cursor()
 
# create query 
sql = "select * from mytable" 
 
# execute query 
dbcursor.execute(sql)
 
# get query results 
results = dbcursor.fetchall()
 
# display results 
if len(results) == 0:
    print "there were no results." 
else:
    print "results:" 
    for item in results:
        print item
 
# clean up / close connection 
dbconnection.close()
 

No comments:

Post a Comment