Database Reference
In-Depth Information
catch
(
PDOException
$e
)
{
print
(
"Cannot connect to server
\n
"
);
print
(
"Error code: "
.
$e
->
getCode
()
.
"
\n
"
);
print
(
"Error message: "
.
$e
->
getMessage
()
.
"
\n
"
);
exit
(
1
);
}
$dbh
=
NULL
;
print
(
"Disconnected
\n
"
);
?>
The
require_once
statement accesses the
Cookbook.php
file that is required to use the
Cookbook
class.
require_once
is one of several PHP file-inclusion statements:
•
require
and
include
instruct PHP to read the named file. They are similar, but
require
terminates the script if the file cannot be found;
include
produces only a
warning.
•
require_once
and
include_once
are like
require
and
include
except that if the
file has already been read, its contents are not processed again. This is useful for
avoiding multiple-declaration problems that can easily occur when library files in‐
clude other library files.
Python
Python libraries are written as modules and referenced from scripts using
import
state‐
ments. To create a method for connecting to MySQL, write a module file,
cookbook.py
(Python module names should be lowercase):
# cookbook.py: library file with utility method for connecting to MySQL
# using the Connector/Python module
import
mysql.connector
conn_params
=
{
"database"
:
"cookbook"
,
"host"
:
"localhost"
,
"user"
:
"cbuser"
,
"password"
:
"cbpass"
,
}
# Establish a connection to the cookbook database, returning a connection
# object. Raise an exception if the connection cannot be established.
def
connect
():
return
mysql
.
connector
.
connect
(
**
conn_params
)
The filename basename determines the module name, so the module is called
cook
book
. Module methods are accessed through the module name; thus, import the
cook
book
module and invoke its
connect()
method like this: