If you’re going to be working in a web environment using Python, chances are that you’ll be using MySQL as database management system. That is why software developer Jeremy Morgan of Silicon Forest created this tutorial on how to connect to a MySQL database using Python, which is our featured tutorial of the day.
I’ll be posting the whole code below for you to scrutinize and study but if you what a step-by-step explanation on what each line of code represents and what it does, check out Jeremy’s POST.
#!/usr/bin/python # datademo.py # a simple script to pull some data from MySQL import MySQLdb db = MySQLdb.connect(host="localhost", user="root", passwd="", db="test") #create a cursor for the select cur = db.cursor() #execute an sql query cur.execute("SELECT firstname,lastname FROM test.name") ##Iterate for row in cur.fetchall() : #data from rows firstname = str(row[0]) lastname = str(row[1]) #print print "This Person's name is " + firstname + " " + lastname # close the cursor cur.close() # close the connection db.close ()