JDBC represents a connection
to a database through the
interface. Thus, connecting to MySQL
requires you to get an instance of the
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 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. 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, ...