CRUD with Python & MySQL (Write)

For details on getting Python and MySQL wired, check out the previous post. This post is about performing create, update, and delete operations against a MySQL database from within a Python script. First, let’s create a new row in the property table of a database named iRent:

#!/usr/bin/env python

import MySQLdb

# Instantiate connection object and connect to MySQL database
db = MySQLdb.connect("localhost", "username", "password", "irent")

# Instantiate cursor object
cursor = db.cursor()

# Prepare a dml statement
sql = "insert into property (address_line_1, user_id, type_id) \
        values ('%s', '%d', '%d')" % ('234 Sathorn Rd', 1, 1)

try:
    # Execute dml and commit changes
    cursor.execute(sql)
    db.commit()
    
except:
    # Rollback changes
    db.rollback()

# Close database connection
db.close()

Continue reading