Database Reference
In-Depth Information
#!/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 topic 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
clause that contains the error-handling code. Exceptions that occur at the top level of a
script (that is, outside of any
try
statement) are caught by the default exception handler,
which prints a stack trace and exits.
Recipe 2.2
discusses error handling further.
The
else
clause contains statements that execute if the
try
clause produces no excep‐
tion. It's used here to close the successfully opened connection.
Because the
connect()
call uses named arguments, their order does not matter. If you
omit the
host
argument from the
connect()
call, its default value is
127.0.0.1
. To select
no default database, omit the
database
argument or pass a
database
value of
""
(the
empty string) or
None
.
Another way to connect is to specify the parameters using a Python dictionary and pass
the dictionary to
connect()
: