Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
MySQL for Python

You're reading from   MySQL for Python Integrating MySQL and Python can bring a whole new level of productivity to your applications. This practical tutorial shows you how with examples and explanations that clarify even the most difficult concepts.

Arrow left icon
Product type Paperback
Published in Sep 2010
Publisher Packt
ISBN-13 9781849510189
Length 440 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Albert Lukaszewski Albert Lukaszewski
Author Profile Icon Albert Lukaszewski
Albert Lukaszewski
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

MySQL for Python
Credits
About the Author
About the Reviewers
Preface
1. Getting Up and Running with MySQL for Python FREE CHAPTER 2. Simple Querying 3. Simple Insertion 4. Exception Handling 5. Results Record-by-Record 6. Inserting Multiple Entries 7. Creating and Dropping 8. Creating Users and Granting Access 9. Date and Time Values 10. Aggregate Functions and Clauses 11. SELECT Alternatives 12. String Functions 13. Showing MySQL Metadata 14. Disaster Recovery Index

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)

An alternative way of rendering the last two lines is to leave the value insertion to the execute() function. Instead of using %(fish, price) at the end of...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image