Database Reference
In-Depth Information
conn_params
=
{
"database"
:
"cookbook"
,
"host"
:
"localhost"
,
"user"
:
"cbuser"
,
"password"
:
"cbpass"
,
}
conn
=
mysql
.
connector
.
connect
(
**
conn_params
)
print
(
"Connected"
)
This topic generally uses that style from now on.
Additional connection parameters.
To specify the path to a socket file for local host con‐
nections on Unix, omit the
host
parameter and provide a
unix_socket
parameter:
conn_params
=
{
"database"
:
"cookbook"
,
"unix_socket"
:
"/var/tmp/mysql.sock"
,
"user"
:
"cbuser"
,
"password"
:
"cbpass"
,
}
conn
=
mysql
.
connector
.
connect
(
**
conn_params
)
print
(
"Connected"
)
To specify the port number for TCP/IP connections, include the
host
parameter and
provide an integer-valued
port
parameter:
conn_params
=
{
"database"
:
"cookbook"
,
"host"
:
"127.0.0.1"
,
"port"
:
3307
,
"user"
:
"cbuser"
,
"password"
:
"cbpass"
,
}
conn
=
mysql
.
connector
.
connect
(
**
conn_params
)
Java
Database programs in Java use the JDBC interface, together with a driver for the par‐
ticular database engine you want to access. That is, the JDBC architecture provides a
generic interface used in conjunction with a database-specific driver.
Java programming requires a Java Development Kit (JDK), and you must set your
JAVA_HOME
environment variable to the location where your JDK is installed. To write
MySQL-based Java programs, you'll also need a MySQL-specific JDBC driver. Programs
in this topic use MySQL Connector/J. To obtain it if it's not already installed, see the
Preface. For information about obtaining a JDK and setting
JAVA_HOME
, read “Executing
Programs from the Command Line” on the companion website (see the
Preface
).
The following Java program,
Connect.java
, connects to the MySQL server, selects
cook
book
as the default database, and disconnects: