Updating a Database : MySQL « Database « Python






Updating a Database


import MySQLdb
import MySQLdb.cursors

def get_column_name( data, prompt, names ) :
    value=-1
    while value == -1:
        idx = 1
        for col in data :
            print str(idx) + ": " + col
            names.append( col )
            idx = idx + 1
        value = int( raw_input(prompt) )
        if value < 1 or value >= idx :
            value = -1
    return value


conn = MySQLdb.Connect(
    host='localhost', user='python-test',
    passwd='python', db='python-test')
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

cursor.execute("SELECT * FROM books")
data = cursor.fetchone()

names = []
old_value = get_column_name( data, "Which column do you want to change records for? ", names )
names = []
new_value = get_column_name( data, "Which column do you want to change records to? ", names )

old_val = raw_input("What value do you want to change for " + names[old_value-1] + ": ")
new_val = raw_input("What value do you want to change to for " + names[new_value-1] + ": ")

stmt = "UPDATE books SET " + names[new_value-1] + " = '"+ new_val + "' WHERE " + names[old_value-1] + " = '" + old_val + "'"
print stmt
cursor.execute(stmt)
print "Rows affected: " + str(cursor.rowcount)


cursor.close()
conn.commit()
conn.close()

 








Related examples in the same category

1.Reading from a Database
2.Writing to a Database