Database Reference
In-Depth Information
import
cookbook
conn
=
cookbook
.
connect
();
The Python interpreter searches for modules in directories named in the
sys.path
variable. To check the default value of
sys.path
on your system, run Python interac‐
tively and enter a few commands:
%
python
>>>
import sys
>>>
sys.path
If you install
cookbook.py
in one of the directories named by
sys.path
, your scripts will
find it with no special handling. If you install
cookbook.py
somewhere else, you must
set the
PYTHONPATH
environment variable, as discussed in the introductory part of this
recipe.
After installing the
cookbook.py
library file, try it from a test harness script,
harness.py
:
#!/usr/bin/python
# harness.py: test harness for cookbook.py library
import
mysql.connector
import
cookbook
try
:
conn
=
cookbook
.
connect
()
print
(
"Connected"
)
except
mysql
.
connector
.
Error
as
e
:
print
(
"Cannot connect to server"
)
print
(
"Error code:
%s
"
%
e
.
errno
)
print
(
"Error message:
%s
"
%
e
.
msg
)
else
:
conn
.
close
()
print
(
"Disconnected"
)
The
cookbook.py
file imports the
mysql.connector
module, but a script that imports
cookbook
does not thereby gain access to
mysql.connector
. If the script needs Con‐
nector/Python-specific information (such as
mysql.connector.Error
), the script itself
must import
mysql.connector
.
If you want a script to die if an error occurs without checking for an exception yourself,
write the script body like this:
conn
=
cookbook
.
connect
()
print
(
"Connected"
)
conn
.
close
()
print
(
"Disconnected"
)
Java
Java library files are similar to Java programs in most ways: