Retrieving Entries from a MySQL Database


import MySQLdb myDB = MySQLdb.connect(host="127.0.0.1", port=3306, db="schedule") cHandler = myDB.cursor() sqlCommand = "SELECT * FROM Arrivals" cHandler.execute(sqlCommand) results = cHandler.fetchall() for row in results:    cityList.append(row[0])

Once you have connected to a MySQL database and got a SQL command cursor object, retrieving entries from the database is just a matter of sending the appropriately formatted SQL commands to the server.

First, connect to the server using the MySQLdb modules connect function, and then use the MySQL database object to get a cursor object. In the sample code, all entries are retrieved together by executing the SELECT * FROM <tablename> SQL command using the execute function of the cursor object.

Note

The SELECT SQL command returns entries as a list of lists. Because we know that the field structure of the table is "city, flight, time," each field can be accessed directly using index 0, 1, and 2, respectively.


import MySQLdb #Connect to database myDB = MySQLdb.connect(host="127.0.0.1", \                        port=3306, db="schedule") #Get cursor object cHandler = myDB.cursor() #Send select request for specific entries sqlCommand = "SELECT * FROM Arrivals \  WHERE city = 'Dallas'" cHandler.execute(sqlCommand) #View results results = cHandler.fetchall() print results #Send select request for all entries sqlCommand = "SELECT * FROM Arrivals" cHandler.execute(sqlCommand) #View results results = cHandler.fetchall() print results #Process rows into lists cityList = [] flightList = [] timeList = [] for row in results:     cityList.append(row[0])     flightList.append(row[1])     timeList.append(row[2]) print "\nArrivals" print "=============================================" x = 0 for flight in flightList:     print ("Flight %s arrives from %s at %s" % \            (flight, cityList[x],  timeList[x]))     x+=1 myDB.close()


MySQL_get.py

(('Dallas', '1144', '230pm'),) (('Dallas', '1144', '230pm'), ('Los Angeles', '1045', '320pm'), ('New York', '1520', '420pm')) Arrivals ============================================= Flight 1144 arrives from Dallas at 230pm Flight 1045 arrives from Los Angeles at 320pm Flight 1520 arrives from New York at 420pm


Output from MySQL_get.py code



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net