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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
MySQL for Python
MySQL for Python

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.

eBook
$22.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

MySQL for Python

Chapter 2. Simple Querying

Record retrieval is without doubt the most common activity employed with regard to MySQL and other relational databases. Like most computer programs, MySQL functions on the basis of being invoked with parameters and returning results in accordance with them. As we seen, Python acts as an intermediary to that process. We can use it to access MySQL, login, and connect to a database of our choice.

In this chapter, we will look at the following:

  • Forming a MySQL query directly

  • Passing a query to MySQL

  • User-defined variables in a MySQL query

  • Determining characteristics of a database and its tables

  • Changing queries dynamically, without user input

Working through each of these points will help you at the end of the chapter, when we get to the project: a command-line search tool.

A brief introduction to CRUD


The four basic functions of any persistent storage system like MySQL spell CRUD:

  • Create

  • Read

  • Update

  • Delete

These are key concepts, which each of the basic MySQL commands reflect.

There is nothing technical about the words themselves, but the concepts are very important. They represent the four activities that you can expect to be able to do in every relational database system you use. There are several alternatives to this acronym and keyword series (for example, SCUD for "select, create, update, and delete" or SIDU for "select, insert, delete, and update"). The point of each of these is that database functionality boils down to two sets of opposing activities:

  • Creating and deleting database objects (for example, databases, tables, records)

  • Inserting and reading data (that is writing and reading)

Each of these will be addressed in the coming chapters. In this one, we start with reading data using SELECT.

Forming a query in MySQL


In order to best understand how to submit a query through MySQL for Python, it is important to ensure you understand how to submit a query in MySQL itself. The similarities between the two outnumber the differences, but the first may seem confusing if you don't properly understand the second.

MySQL statements have a basic structure. In following a set structure, they are formed like natural language statements. Being a computer program, it understandably responds very poorly to informational statements and only moderately well to questions. Almost all MySQL statements have an imperatival tone, expressing your command. This is reflective of the client-server relationship. The computer is the servant who exists to do the bidding of yourself as the client or, if you prefer, master.

The syntactic structure of a simple MySQL statement is not that different from the language you use every day. Where English would have:

  • Give me everything from the staff table!

MySQL would need...

Passing a query to MySQL


We have just seen how to form a query for a generic MySQL session. While that was not particularly difficult, using MySQL for Python is even easier. For this next section, we will be working against a database fish with a table menu that has the following contents:

+----+----------------+-------+
| id | name           | price |
+----+----------------+-------+
|  1 | tuna           |  7.50 | 
|  2 | bass           |  6.75 | 
|  3 | salmon         |  9.50 | 
|  4 | catfish        |  5.00 | 
|  5 | trout          |  6.00 | 
|  6 | haddock        |  6.50 | 
|  7 | yellowfin tuna | 12.00 | 
+----+----------------+-------+

As discussed in Chapter 1, Python's interface with MySQL requires a cursor. It is through the cursor object that we pass commands to MySQL. So, we import MySQL for Python, log into our database fish and create the cursor as follows:

import MySQLdb
mydb = MySQLdb.connect(host = 'localhost', 
                       user = 'skipper', 
                  ...

Using user-defined variables


What if you want to specify a different price floor every time you run the search? What if you didn't want to use a floor but specify the price exactly? What if you wanted to reuse part of the statement and automate queries by fish name instead of retrieving all of them at once? Under such circumstances, you need to be able to handle variables in your SELECT statements.

MySQL for Python passes variables to MySQL in the same way that Python formats other kinds of output. If we wanted to specify just the floor of the search, we would assign the variable as any other and pass it to the execute() method as a string. Consider the following snippet from a Python terminal session:

>>> value = "7.50"
>>> command = cur.execute("""SELECT * FROM menu WHERE price = %s""" %(value))
>>> results = cur.fetchall()
>>> for record in results:
...     print record[0], ". ", record[1], "(%s)" %record[2]
... 
1 .  tuna (7.50)

If we wanted the user...

Determining characteristics of a database and its tables


For reasons of security, one simply must not rely on the user to know the database structure in order to make a query. Even if the user does, one should never write code that assumes this. You never know who the user is and what nefarious results will be sought by the user. Given that there are more people than you know who want to break your code and exploit your data, it is best practice to restrict the user's knowledge of the database and to verify the integrity of any data the end user inputs into the program.

Without doubt, the best way to restrict the user's knowledge of the database is to provide set options for the user in a way that the user cannot edit. In graphical user interfaces (GUIs), this is done most often by drop-down menus and radio buttons. In terminal-based programs, one lists the options. The former keeps the programmer in control of the environment and so funnels the user to the point of either choosing the set...

Changing queries dynamically


But what if the user does not want to submit a precise query but needs a list of the possibilities? There are a couple of ways to clarify the search. We could first keep a list of the common search queries. This is something done often by the likes of Google and Yahoo!. This works very well with large datasets served through web servers because it uses a static list of terms and simply culls them out. For more dedicated applications, one can use MySQL's pattern matching ability to present known options on-the-fly.

Pattern matching in MySQL queries

Where Python's regular expression engine is very robust, MySQL supports the two following metacharacters for forming regular expressions:

  • %: Zero or more characters matched in aggregate

  • _ : Any single character matched individually

Pattern matching is always a matter of comparison. Therefore, with either of these, never use operators of equality.

SELECT * FROM menu WHERE name = 's%'; 		        WRONG
SELECT * FROM menu WHERE...

Project: A command-line search utility


This chapter has been about querying MySQL from Python. As a project to finish it out, we will build a command-line search utility. Rather than ask the user for the search term, we will expect the user to state the term as an argument for the command-line invocation.

Note

With a bit more code for this project, we could create a GUI for this program. GUI programming increases the complexity of the code. How much more complex it gets depends on the library being used, but it is nonetheless unnecessary for what we need to illustrate in this project. Until we are certain that we have a database and can connect to it, it is best to keep it simple.

Now, it is true that we could simply take input and feed it through MySQL for Python as a generic SELECT * statement. The logic for this bare bones implementation has been illustrated previously to a great extent. We can create something a bit more sophisticated.

The following characteristics should apply to our search...

Room to grow


While the projection specification that we set for ourselves is fulfilled, there is more that can be done on this program to make it more serviceable in a production environment. Some areas that you might look at for further practice are:

  • Set the host, database, username, and password from command-line options. You will naturally need to error-check each of them. You will probably want to use the getpass module to accept the password in production environments.

  • Set an option for the column variable and testing whether that column exists in the chosen database.

  • Set up error-checking for the results itself.

The world database has a few other tables besides City. Can you aggregate their records in Python without using a JOIN statement?

Summary


It almost goes without saying that querying and data retrieval is the bread and butter of database programming. In this chapter, we have covered the formation of a MySQL query and how to pass it from Python. We also saw how to use user-defined variables to allow dynamic formation of statements rather than pre-configured queries. In order to adjust our program flow, we also saw how to determine the characteristics of a database and its tables from within Python. Finally, we programmed a command-line search utility that returns data of the user's choice in two different formats.

In the next chapter, we will look at the flipside of the SELECT command, INSERT.

Left arrow icon Right arrow icon

Key benefits

  • Implement the outstanding features of Python's MySQL library to their full potential
  • See how to make MySQL take the processing burden from your programs
  • Learn how to employ Python with MySQL to power your websites and desktop applications
  • Apply your knowledge of MySQL and Python to real-world problems instead of hypothetical scenarios
  • A manual packed with step-by-step exercises to integrate your Python applications with the MySQL database server

Description

Python is a dynamic programming language, which is completely enterprise ready, owing largely to the variety of support modules that are available to extend its capabilities. In order to build productive and feature-rich Python applications, we need to use MySQL for Python, a module that provides database support to our applications. Although you might be familiar with accessing data in MySQL, here you will learn how to access data through MySQL for Python efficiently and effectively.This book demonstrates how to boost the productivity of your Python applications by integrating them with the MySQL database server, the world's most powerful open source database. It will teach you to access the data on your MySQL database server easily with Python's library for MySQL using a practical, hands-on approach. Leaving theory to the classroom, this book uses real-world code to solve real-world problems with real-world solutions.The book starts by exploring the various means of installing MySQL for Python on different platforms and how to use simple database querying techniques to improve your programs. It then takes you through data insertion, data retrieval, and error-handling techniques to create robust programs. The book also covers automation of both database and user creation, and administration of access controls. As the book progresses, you will learn to use many more advanced features of Python for MySQL that facilitate effective administration of your database through Python. Every chapter is illustrated with a project that you can deploy in your own situation.By the end of this book, you will know several techniques for interfacing your Python applications with MySQL effectively so that powerful database management through Python becomes easy to achieve and easy to maintain.

Who is this book for?

This book is meant for intermediate users of Python who want hassle-free access to their MySQL database through Python. If you are a Python programmer who wants database-support in your Python applications, then this book is for you. This book is a must-read for every focused user of the MySQL for Python library who wants real-world applications using this powerful combination of Python and MySQL.

What you will learn

  • Explore the various means to install MySQL for Python, from using an egg to unrolling a tarball
  • Query the database and retrieve records through MySQL for Python
  • Implement insertion of data into a MySQL database in Python
  • Carry out error-handling in MySQL for Python in order to ensure the robustness of programs
  • Use secure logging techniques to record how your users use your programs
  • Carry out record-by-record retrieval to save a lot of overhead while retrieving data
  • Handle insertion of large amounts of data using iteration and the executemany function
  • Automate the creation and removal of databases and tables using MySQL for Python
  • Use the MySQL for Python library to automate user creation and to administer access controls
  • Log user activity with MySQL for Python by using MySQL s date and time support
  • See how to revise database programs to include more functionality
  • Use aggregate functions to make MySQL take the burden off your web server
  • Save time and processing resources by scripting JOINs and subqueries

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 21, 2010
Length: 440 pages
Edition : 1st
Language : English
ISBN-13 : 9781849510196
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Sep 21, 2010
Length: 440 pages
Edition : 1st
Language : English
ISBN-13 : 9781849510196
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
MySQL for Python
$54.99
Python 3 Object Oriented Programming
$54.99
Mastering Object-oriented Python
$48.99
Total $ 158.97 Stars icon

Table of Contents

14 Chapters
Getting Up and Running with MySQL for Python Chevron down icon Chevron up icon
Simple Querying Chevron down icon Chevron up icon
Simple Insertion Chevron down icon Chevron up icon
Exception Handling Chevron down icon Chevron up icon
Results Record-by-Record Chevron down icon Chevron up icon
Inserting Multiple Entries Chevron down icon Chevron up icon
Creating and Dropping Chevron down icon Chevron up icon
Creating Users and Granting Access Chevron down icon Chevron up icon
Date and Time Values Chevron down icon Chevron up icon
Aggregate Functions and Clauses Chevron down icon Chevron up icon
SELECT Alternatives Chevron down icon Chevron up icon
String Functions Chevron down icon Chevron up icon
Showing MySQL Metadata Chevron down icon Chevron up icon
Disaster Recovery Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.6
(10 Ratings)
5 star 20%
4 star 50%
3 star 10%
2 star 10%
1 star 10%
Filter icon Filter
Top Reviews

Filter reviews by




RandomUser2221 Jan 25, 2011
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I must say that I'm rather impressed at the variety of topics that the book covers.It starts off with the basics of setting up MySQL for your testing/development needs by going over several of the common installation and configuration methods. After that it's a quick intro for connection methods and simple error reporting for connections. The author gives a quick intro to CRUD and how it relates to databases and python before heading into the common tasks of simple queries. I was surprised to see some database profiling discussion; which is rather handy for a new coder or a person new to MySQL. Once the basics of Inserts/Selects/Updates/Deletes are covered, which is a rather quick read, there is a welcome discussion of transactions and commit methods - if you do not read this section and are new to MySQL then believe me, you're missing a very important topic. Most people will gloss over the basics and head right to the more advanced chapters that feature exception handling, the all too common "the mysql server has gone away" error, date&time functions, aggregate functions, and metadata queries. These chapters were the most interesting to me as they covered some great code for python that I have not yet played around with. Previously I've done a lot of work on those topics with perl and php so seeing how they were done in python was a great treat. The code is concise, easy to read, and well explained.A number of topics cover the time saving solutions that no one should be without. Namely, bulk data inserting, data formatting, row iteration, and CSV parsing. Logging methods for access and changes to the database are also covered, and in the end will save your development cycle a lot of time when you are troubleshooting app-to-db interaction.Two chapters will be of interest to DBAs in particular, and possibly not as interesting to pure developers, of which these are the Disaster Recovery and MySQL Administration topics. The author covers offline backups as well as online hot backups, two sections that no DBA should be without. The code for this type of work is covered in a decent amount of discussion but, along with the other chapters in the book, the theory and background of the topic is also discussed which gives the new reader an understanding of "why" and not just left with the "how". The administration section of the book covers user creation and permissions management, along with a bit of background on security involved with that task, and also goes into quite a lot of coverage on web-based GUI administration and command line interaction for admin purposes.Overall I enjoyed the contents of the book and would recommend taking a look if you are new to Python and MySQL or are even looking for a quick reference to the common tasks of database driven application development. This book does not cover the common ORM database interactions you're likely to see in an app like Django or Pylons, but it will give you a solid foundation on how python and MySQL interact without an abstraction layer. If you are writing quick admin code or building your own database interaction layer, then this book would do well to be in your collection.
Amazon Verified review Amazon
sujin wie Jun 24, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
There are a little simple example.But it was to explain detail and to useful information for me..So I recommended that book!
Amazon Verified review Amazon
Bernard Peek Apr 10, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A useful different approach to implementing data-driven applications with Python and MySQL. The target audience is python developers who have never worked with relational databases.
Amazon Verified review Amazon
Mark Jaffe Feb 22, 2011
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a comprehensive tutorial on using the mysql module for Python and for using MySQL ingeneral. Although the author's native language may not be English, I found the oddly-phrasedtext to be quite understandable and easy to follow. I have been a MySQL user for a number ofyears now, and would have welcomed this book to my bookshelf several years ago when I wastrying to solve some of the problems laid out in detail in this book.Topics covered include creating and dropping databases, users and tables, inserting, updatingand deleting data in tables, and manipulating user permissions. A functioning PHP applicationis presented in a few chapters which can be used to demonstrate the examples used throughoutthe book. The publisher's Web site provides downloadable code for the examples.
Amazon Verified review Amazon
Dalli Vamsidhar Reddy May 05, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Very nice book for data manipulation in MySQL through Python programming
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.