In this section we’ll review the basic methods provided in the
MySQLdb extension for
establishing a connection to a MySQL server and processing simple SQL
statements. These methods provide a foundation that we can use when
working with stored programs. If you are already familiar with the
MySQLdb extension, then you might
like to skip forward to "Using
Stored Programs with MySQLdb,” later in the chapter.
Before we can use
we need to import the module. We can then use the
connect() method of the base
MySQLdb class to create a connection
takes five arguments—
port—which identify the MySQL server,
account, and database to which we intend to connect. Each of the
arguments is optional, with sensible default values (
localhost for the hostname, for
Example 16-1 illustrates the basic technique.
import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "secret", db = "mysql", port=3306)
Usually we will want to retrieve connection details from the command line. Python includes a powerful and useful command-line option parser that allows us to do this. Example 16-2 shows how to retrieve MySQL connection details from the command line and set up a connection.
import MySQLdb from optparse import OptionParser parser = OptionParser( ) parser.add_option("-u","--username", ...