Connecting to MySQL

JDBC represents a connection to a database through the Connection interface. Thus, connecting to MySQL requires you to get an instance of the Connection interface from your JDBC driver. JDBC supports two ways of getting access to a database connection:

  • Through a JDBC data source

  • Using the JDBC driver manager

The data source method is preferred for connecting to a database. Data sources come from the Optional Package, so support for them is still spotty. No matter what environment you are in, you can rely on driver manager connectivity.

Data source connectivity

Data source connectivity is very simple. In fact, the following code makes a connection to any database; it is not specific to MySQL:

Context ctx = new InitialContext(  );
DataSource ds = (DataSource)ctx.lookup("jdbc/myds");
Connection conn = ds.getConnection("userid", "password");

The first line in this example actually comes from the Java Naming and Directory Interface (JNDI) API. JNDI is an API that provides access to naming and directory services.[3] Naming and directory services are specialized data stores that enable you to associate related data under a familiar name. In a Windows environment, for example, a network printer is stored in Microsoft ActiveDirectory under a name. To print to the networked color printer, a user does not need to know all the technical details about the printer. Those details are stored in the directory. The user simply needs to know the name of the printer. The directory, ...

Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.