barronmo a écrit : > I'm new to programming and even newer to Python and would be grateful > for some help on what has been a tough problem for me. The project I > am working on is an electronic medical record using MySQL/Python. I'm > currrently working on a module that looks up a patient's name based on > input from the user. > > My goal is a lookup based on the first 2 or 3 letters of the patient's > last name. The matching results would appear as numbered choices so > that the user would choose only a number to then access various parts > of the patient's record. The results might look like this for user > input "smi": > > 1 387 John Smith > 2 453 Jane Smith > 3 975 Joe Smithton > > Here is a copy of what I have so far, name_lookup.py: > > > import MySQLdb > > def name_find(namefrag): > > conn = MySQLdb.connect(host = "localhost", > user = "root", > passwd = "n85", > db = "meds")
Opening (and closing) a connection to the RDBMS on each and every function is certainly not the best way to go. > cursor = conn.cursor(MySQLdb.cursors.DictCursor) > cursor.execute("SELECT patient_ID, firstname, lastname FROM > demographics WHERE lastname LIKE '"+ str(namefrag)+"%'") Please re-read both the db-api and MySQLdb docs. You should not build the whole query this way, but instead use (db module specific) plaeholders and pass actual params as a tuple, ie (if I correctly remember MySQLdb specificities): cursor.execute( "SELECT patient_ID, firstname, lastname FROM " \ + " demographics WHERE lastname LIKE '%s%%'), (namefrag, ) ) > results = cursor.fetchall() > for row in results: Some db modules let you iterate directly over the cursor. Check if it's the case with MySQLdb. If so, you may want: for row in cursor: instead. > print "%s %s %s %s" % (row["patient_ID"], > row["firstname"], row["lastname"]) Python has better to offer wrt/ string formatting (assuming patient_ID is an integer): print "%(patient_ID)03d %(firstname)s, %(lastname)s" % row > > Thanks in advance for any help. wrt/ (what I guess is) your (very implicit) question, you may want to have a look at enumerate(iterable): for index, item in enumerate(cursor): #or:enumerate(cursor.fetchall()): print i, item HTH -- http://mail.python.org/mailman/listinfo/python-list