Using user-defined variables

Just as in data retrieval, it is inevitable that you will want to utilize user input when inserting data into MySQL. MySQL for Python provides a consistent, Pythonic interface for this.

We use the same string conversion specifier as we did when incorporating user input into our SELECT statements in the previous chapter. Using the fish database, if we assume that the user gives us the name of the fish and the cost, we can code a user-defined INSERT statement as follows:

import MySQLdb, sys mydb = MySQLdb.connect(host = 'localhost', user = 'skipper', passwd = 'secret', db = 'fish') cur = mydb.cursor() fish = sys.argv[1] price = sys.argv[2] statement = """INSERT INTO menu(name, price) VALUES(%s, %s)""" %(fish, price) cur.execute(statement) ...

Get MySQL for Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.