• Aucun résultat trouvé

Connecting, Selecting a Database, and Disconnecting

Dans le document MySQL Cookbook (Page 57-70)

MySQL Client API Architecture

2.1. Connecting, Selecting a Database, and Disconnecting

Problem

You need to establish a connection to the database server and shut down the connection when you’re done.

Solution

Each API provides routines for connecting and disconnecting. The connection routines require that you provide parameters specifying the host on which the MySQL server is running and the MySQL account to use. You can also select a default database.

Discussion

This section shows how to perform some fundamental operations common to most MySQL programs:

Establishing a connection to the MySQL server

Every program that uses MySQL does this, no matter which API you use. The details on specifying connection parameters vary between APIs, and some APIs provide more flexibility than others. However, there are many common parameters, such as the host on which the server is running, and the username and password of the MySQL account to use for accessing the server.

Selecting a database

Most MySQL programs select a default database.

Disconnecting from the server

Each API provides a way to close an open connection. It’s best to do so as soon as you’re done using the server. If your program holds the connection open longer than necessary, the server cannot free up resources allocated to servicing the con‐

2.1. Connecting, Selecting a Database, and Disconnecting | 29

nection. It’s also preferable to close the connection explicitly. If a program simply terminates, the MySQL server eventually notices, but an explicit close on the user end enables the server to perform an immediate orderly close on its end.

This section includes example programs that show how to use each API to connect to the server, select the cookbook database, and disconnect. The discussion for each API also indicates how to connect without selecting any default database. This might be the case if you plan to execute a statement that doesn’t require a default database, such as SHOWVARIABLES or SELECTVERSION(). Or perhaps you’re writing a program that enables the user to specify the database after the connection has been made.

The scripts shown here use localhost as the hostname. If they pro‐

duce a connection error indicating that a socket file cannot be found, try changing localhost to 127.0.0.1, the TCP/IP address of the local host. This tip applies throughout the book.

Perl

To write MySQL scripts in Perl, the DBI module must be installed, as well as the MySQL-specific driver module, DBD::mysql. To obtain these modules if they’re not already installed, see the Preface.

The following Perl script, connect.pl, connects to the MySQL server, selects cookbook as the default database, and disconnects:

#!/usr/bin/perl

# connect.pl: connect to the MySQL server use strict;

use warnings;

use DBI;

my $dsn = "DBI:mysql:host=localhost;database=cookbook";

my $dbh = DBI->connect ($dsn, "cbuser", "cbpass") or die "Cannot connect to server\n";

print "Connected\n";

$dbh->disconnect ();

print "Disconnected\n";

To try connect.pl, locate it under the api directory of the recipes distribution and run it from the command line. The program should print two lines indicating that it con‐

nected and disconnected successfully:

% perl connect.pl Connected

Disconnected

30 | Chapter 2: Writing MySQL-Based Programs

For background on running Perl programs, read “Executing Programs from the Com‐

mand Line” on the companion website (see the Preface).

The usestrict line turns on strict variable checking and causes Perl to complain about any variables that are used without having been declared first. This precaution helps find errors that might otherwise go undetected.

The usewarnings line turns on warning mode so that Perl produces warnings for any questionable constructs. Our example script has none, but it’s a good idea to get in the habit of enabling warnings to catch problems that occur during the script development process. usewarnings is similar to specifying the Perl -w command-line option, but provides more control over which warnings to display. (For more information, execute a perldoc warnings command.)

The useDBI statement tells Perl to load the DBI module. It’s unnecessary to load the MySQL driver module (DBD::mysql) explicitly. DBI does that itself when the script connects to the database server.

The next two lines establish the connection to MySQL by setting up a data source name (DSN) and calling the DBI connect() method. The arguments to connect() are the DSN, the MySQL username and password, and any connection attributes you want to specify. The DSN is required. The other arguments are optional, although usually it’s necessary to supply a username and password.

The DSN specifies which database driver to use and other options that indicate where to connect. For MySQL programs, the DSN has the format DBI:mysql:options. The second colon in the DSN is required even if you specify no following options.

Use the DSN components as follows:

• The first component is always DBI. It’s not case sensitive.

• The second component tells DBI which database driver to use, and it is case sensi‐

tive. For MySQL, the name must be mysql.

• The third component, if present, is a semicolon-separated list of name=value pairs that specify additional connection options, in any order. For our purposes, the two most relevant options are host and database, to specify the hostname where the MySQL server is running and the default database.

Based on that information, the DSN for connecting to the cookbook database on the local host localhost looks like this:

DBI:mysql:host=localhost;database=cookbook

If you omit the host option, its default value is localhost. These two DSNs are equivalent:

2.1. Connecting, Selecting a Database, and Disconnecting | 31

DBI:mysql:host=localhost;database=cookbook DBI:mysql:database=cookbook

To select no default database, omit the database option.

The second and third arguments of the connect() call are your MySQL username and password. Following the password, you can also provide a fourth argument to specify attributes that control DBI’s behavior when errors occur. With no attributes, DBI by default prints error messages when errors occur but does not terminate your script.

That’s why connect.pl checks whether connect() returns undef, which indicates failure:

my $dbh = DBI->connect ($dsn, "cbuser", "cbpass") or die "Cannot connect to server\n";

Other error-handling strategies are possible. For example, to tell DBI to terminate the script if an error occurs in any DBI call, disable the PrintError attribute and enable RaiseError instead:

my $dbh = DBI->connect ($dsn, "cbuser", "cbpass",

{PrintError => 0, RaiseError => 1});

Then you need not check for errors yourself. The trade-off is that you also lose the ability to decide how your program recovers from errors. Recipe 2.2 discusses error handling further.

Another common attribute is AutoCommit, which sets the connection’s auto-commit mode for transactions. MySQL enables this by default for new connections, but we’ll set it from this point on to make the initial connection state explicit:

my $dbh = DBI->connect ($dsn, "cbuser", "cbpass",

{PrintError => 0, RaiseError => 1, AutoCommit => 1});

As shown, the fourth argument to connect() is a reference to a hash of attribute name/

value pairs. An alternative way of writing this code follows:

my $conn_attrs = {PrintError => 0, RaiseError => 1, AutoCommit => 1};

my $dbh = DBI->connect ($dsn, "cbuser", "cbpass", $conn_attrs);

Use whichever style you prefer. Scripts in this book use the $conn_attr hashref to make connect() calls simpler to read.

Assuming that connect() succeeds, it returns a database handle that contains infor‐

mation about the state of the connection. (In DBI parlance, references to objects are called handles.) Later we’ll see other handles such as statement handles, which are as‐

sociated with particular statements. Perl DBI scripts in this book conventionally use

$dbh and $sth to signify database and statement handles.

Additional connection parameters. To specify the path to a socket file for localhost con‐

nections on Unix, provide a mysql_socket option in the DSN:

32 | Chapter 2: Writing MySQL-Based Programs

my $dsn = "DBI:mysql:host=localhost;database=cookbook"

. ";mysql_socket=/var/tmp/mysql.sock";

To specify the port number for non-localhost (TCP/IP) connections, provide a port option:

my $dsn = "DBI:mysql:host=127.0.0.1;database=cookbook;port=3307";

Ruby

To write MySQL scripts in Ruby, the DBI module must be installed, as well as the MySQL-specific driver module. To obtain these modules if they’re not already installed, see the Preface.

The following Ruby script, connect.rb, connects to the MySQL server, selects cook book as the default database, and disconnects:

#!/usr/bin/ruby -w

# connect.rb: connect to the MySQL server require "dbi"

begin

dsn = "DBI:Mysql:host=localhost;database=cookbook"

dbh = DBI.connect(dsn, "cbuser", "cbpass") puts "Connected"

rescue

puts "Cannot connect to server"

exit(1) end

dbh.disconnect puts "Disconnected"

To try connect.rb, locate it under the api directory of the recipes distribution and run it from the command line. The program should print two lines indicating that it con‐

nected and disconnected successfully:

% ruby connect.rb Connected

Disconnected

For background on running Ruby programs, read “Executing Programs from the Com‐

mand Line” on the companion website (see the Preface).

The -w option turns on warning mode so that Ruby produces warnings for any ques‐

tionable constructs. Our example script has no such constructs, but it’s a good idea to get in the habit of using -w to catch problems that occur during the script development process.

2.1. Connecting, Selecting a Database, and Disconnecting | 33

The require statement tells Ruby to load the DBI module. It’s unnecessary to load the MySQL driver module explicitly. DBI does that itself when the script connects to the database server.

To establish the connection, pass a data source name (DSN) and the MySQL username and password to the connect() method. The DSN is required. The other arguments are optional, although usually it’s necessary to supply a username and password.

The DSN specifies which database driver to use and other options that indicate where to connect. For MySQL programs, the DSN typically has one of these formats:

DBI:Mysql:db_name:host_name

DBI:Mysql:name=value;name=value ...

As with Perl DBI, the second colon in the DSN is required even if you specify no fol‐

lowing options.

Use the DSN components as follows:

• The first component is always DBI or dbi.

• The second component tells DBI which database driver to use. For MySQL, the name is Mysql.

• The third component, if present, is either a database name and hostname separated by a colon, or a semicolon-separated list of name=value pairs that specify additional connection options, in any order. For our purposes, the two most relevant options are host and database, to specify the hostname where the MySQL server is running and the default database.

Based on that information, the DSN for connecting to the cookbook database on the local host localhost looks like this:

DBI:Mysql:host=localhost;database=cookbook

If you omit the host option, its default value is localhost. These two DSNs are equiv‐

alent:

DBI:Mysql:host=localhost;database=cookbook DBI:Mysql:database=cookbook

To select no default database, omit the database option.

Assuming that connect() succeeds, it returns a database handle that contains infor‐

mation about the state of the connection. Ruby DBI scripts in this book conventionally use dbh to signify a database handle.

If the connect() method fails, DBI raises an exception. To handle exceptions, put the statements that might fail inside a begin block, and use a rescue clause that contains the error-handling code. Exceptions that occur at the top level of a script (that is, outside

34 | Chapter 2: Writing MySQL-Based Programs

of any begin block) are caught by the default exception handler, which prints a stack trace and exits. Recipe 2.2 discusses error handling further.

Additional connection parameters. To specify the path to a socket file for localhost con‐

nections on Unix, provide a socket option in the DSN:

dsn = "DBI:Mysql:host=localhost;database=cookbook" + ";socket=/var/tmp/mysql.sock"

To specify the port number for non-localhost (TCP/IP) connections, provide a port option:

dsn = "DBI:Mysql:host=127.0.0.1;database=cookbook;port=3307"

PHP

To write PHP scripts that use MySQL, your PHP interpreter must have MySQL support compiled in. If your scripts are unable to connect to your MySQL server, check the instructions included with your PHP distribution to see how to enable MySQL support.

PHP actually has multiple extensions that enable the use of MySQL, such as mysql, the original (and now deprecated) MySQL extension; mysqli, the “MySQL improved” ex‐

tension; and, more recently, the MySQL driver for the PDO (PHP Data Objects) inter‐

face. PHP scripts in this book use PDO. To obtain PHP and PDO if they’re not already installed, see the Preface.

PHP scripts usually are written for use with a web server. I assume that if you use PHP that way, you can copy PHP scripts into your server’s document tree, request them from your browser, and they will execute. For example, if you run Apache as the web server on the host localhost and you install a PHP script named myscript.php at the top level of the Apache document tree, you should be able to access the script by requesting this URL:

http://localhost/myscript.php

This book uses the .php extension (suffix) for PHP script filenames, so your web server must be configured to recognize the .php extension (for Apache, see Recipe 18.2).

Otherwise, when you request a PHP script from your browser, the server simply sends the literal text of the script and that’s what appears in your browser window. You don’t want this to happen, particularly if the script contains the username and password for connecting to MySQL.

PHP scripts often are written as a mixture of HTML and PHP code, with the PHP code embedded between the special <?php and ?> tags. Here is an example:

<html>

<head><title>A simple page</title></head>

<body>

<p>

2.1. Connecting, Selecting a Database, and Disconnecting | 35

<?php

print ("I am PHP code, hear me roar!");

?>

</p>

</body>

</html>

For brevity in examples consisting entirely of PHP code, typically I’ll omit the enclosing

<?php and ?> tags. If you see no tags in a PHP example, assume that <?php and ?>

surround the entire block of code that is shown. Examples that switch between HTML and PHP code do include the tags, to make it clear what is PHP code and what is not.

PHP can be configured to recognize “short” tags as well, written as <? and ?>. This book does not assume that you have short tags enabled and does not use them.

The following PHP script, connect.php, connects to the MySQL server, selects cook book as the default database, and disconnects:

<?php

# connect.php: connect to the MySQL server try

{

$dsn = "mysql:host=localhost;dbname=cookbook";

$dbh = new PDO ($dsn, "cbuser", "cbpass");

print ("Connected\n");

}

catch (PDOException $e) {

die ("Cannot connect to server\n");

}

$dbh = NULL;

print ("Disconnected\n");

?>

To try connect.php, locate it under the api directory of the recipes distribution, copy it to your web server’s document tree, and request it using your browser. Alternatively, if you have a standalone version of the PHP interpreter for use from the command line, execute the script directly:

% php connect.php Connected

Disconnected

For background on running PHP programs, read “Executing Programs from the Com‐

mand Line” on the companion website (see the Preface).

$dsn is the data source name (DSN) that indicates how to connect to the database server.

It has this general syntax:

driver:name=value;name=value ...

36 | Chapter 2: Writing MySQL-Based Programs

The driver value is the PDO driver type. For MySQL, this is mysql.

Following the driver name, semicolon-separated name=value pairs specify connection parameters, in any order. For our purposes, the two most relevant options are host and dbname, to specify the hostname where the MySQL server is running and the default database. To select no default database, omit the dbname option.

To establish the connection, invoke the newPDO() class constructor, passing to it the appropriate arguments. The DSN is required. The other arguments are optional, al‐

though usually it’s necessary to supply a username and password. If the connection attempt succeeds, newPDO() returns a database-handle object that is used to access other MySQL-related methods. PHP scripts in this book conventionally use $dbh to signify a database handle.

If the connection attempt fails, PDO raises an exception. To handle this, put the con‐

nection attempt within a try block and use a catch block that contains the error-handling code, or just let the exception terminate your script. Recipe 2.2 discusses error handling further.

To disconnect, set the database handle to NULL. There is no explicit disconnect call.

Additional connection parameters. To specify the path to a socket file for localhost con‐

nections on Unix, provide a unix_socket option in the DSN:

$dsn = "mysql:host=localhost;dbname=cookbook"

. ";unix_socket=/var/tmp/mysql.sock";

To specify the port number for non-localhost (TCP/IP) connections, provide a port option:

$dsn = "mysql:host=127.0.0.1;database=cookbook;port=3307";

Python

To write MySQL programs in Python, a module must be installed that provides MySQL connectivity for the Python DB API, also known as Python Database API Specification v2.0 (PEP 249). This book uses MySQL Connector/Python. To obtain it if it’s not already installed, see the Preface.

To use the DB API, import the database driver module that you want to use (which is mysql.connector for MySQL programs that use Connector/Python). Then create a database connection object by calling the driver’s connect() method. This object pro‐

vides access to other DB API methods, such as the close() method that severs the connection to the database server.

The following Python script, connect.py, connects to the MySQL server, selects cook book as the default database, and disconnects:

2.1. Connecting, Selecting a Database, and Disconnecting | 37

#!/usr/bin/python

# connect.py: connect to the MySQL server

import mysql.connector try:

conn = mysql.connector.connect(database="cookbook", host="localhost", user="cbuser", password="cbpass") print("Connected")

except:

print("Cannot connect to server") else:

conn.close()

print("Disconnected")

To try connect.py, locate it under the api directory of the recipes distribution and run it from the command line. The program should print two lines indicating that it con‐

nected and disconnected successfully:

% python connect.py Connected

Disconnected

For background on running Python programs, read “Executing Programs from the Command Line” on the companion website (see the Preface).

The import line tells Python to load the mysql.connector module. Then the script attempts to establish a connection to the MySQL server by calling connect() to obtain a connection object. Python scripts in this book conventionally use conn to signify connection objects.

If the connect() method fails, Connector/Python raises an exception. To handle ex‐

ceptions, put the statements that might fail inside a try statement and use an except

ceptions, put the statements that might fail inside a try statement and use an except

Dans le document MySQL Cookbook (Page 57-70)