[Tutor] My code to update database
Eduardo Vieira
eduardo.susan at gmail.com
Fri Jul 10 20:29:52 CEST 2009
Hello! I have the code below to update a database from a csv file. I
have tested one time and it has worked fine, but I'm a bit fearful
that it should work right as I am updating a database and don't want
to cause troubles into the system.
Is this code safe for my personal use?
the update code is in a function, but the rest of the code to connect
and disconnect is outside the function. I thought this was a good idea
because for each line iterated in the csv file, there is a call to the
function to update the database with the data from the csv file. So,
using the 'global' inside the function is ok, or maybe not?
# --- Code starts here ---
import csv
import dbi
import odbc
myconn = odbc.odbc('DSN=MKPT01')
mycursor = myconn.cursor()
def inventory_update(partnumber, quantity, warehouse='00'):
"""Updates a given part number with the corrected quantity"""
global mycursor
mycursor.execute("""UPDATE INVENTORY SET ONHAND = ?
WHERE CODE = ? AND WHSE = ?
""", [quantity, partnumber, warehouse])
if __name__ == "__main__":
csvreader = csv.reader(open('Inventory_tracker.csv', 'rb'),
dialect = 'excel')
for pnumber, qty in csvreader:
print "%s has now %s items in stock" % (pnumber, qty)
inventory_update(pnumber, qty)
mycursor.close()
myconn.commit()
myconn.close()
# --- End ---
I'd appreciate your feedback.
Eduardo
www.expresssignproducts.com
More information about the Tutor
mailing list