Search This Blog

Saturday, January 15, 2011

JDBC:Establishing a Connection

Establishing a Connection
First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:
  • DriverManager: This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.
  • DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.
Note: The samples in this tutorial use the DriverManager class instead of the DataSource class because it is easier to use and the samples do not require the features of the DataSource class.

Using the DriverManager Class

Connecting to your DBMS with the DriverManager class involves calling the method DriverManager.getConnection. The following method, JDBCTutorialUtilities.getConnection, establishes a database connection:
  public Connection getConnection() throws SQLException {
    Connection conn = null;
    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);

    if (this.dbms.equals("mysql")) {
      conn = DriverManager.
        getConnection("jdbc:" + this.dbms + "://" + this.serverName +
                      ":" + this.portNumber + "/", connectionProps);
    } else if (this.dbms.equals("derby")) {
      conn = DriverManager.
        getConnection("jdbc:" + this.dbms + ":" + this.dbName + ";create=true", connectionProps);
    }
    System.out.println("Connected to database");
    return conn;
  }
The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. The following are some examples of database URLs:
  1. MySQL: jdbc:mysql://localhost:3306/, where localhost is the name of the server hosting your database, and 3306 is the port number
  2. Java DB: jdbc:derby:testdb;create=true, where testdb is the name of the database to connect to, and create=true instructs the DBMS to create the database.
    Note: This URL establishes a database connection with the Java DB Embedded Driver. Java DB also includes a Network Client Driver, which uses a different URL.
This method specifies the user name and password required to access the DBMS with a Properties object.
Note:
  • Typically, in the database URL, you also specify the name of an existing database to which you want to connect. For example, the URL jdbc:mysql://localhost:3306/mysql represents the database URL for the MySQL database named mysql. The samples in this tutorial use a URL that does not specify a specific database because the samples create a new database.
  • In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName or DriverManager.registerDriver. These methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.
    Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with one of these initialization methods.)
The method returns a Connection object, which represents a connection with the DBMS or a specific database. Query the database through this object.

Specifying Database Connection URLs

A database connection URL is a string that your DBMS JDBC driver uses to connect to a database. It can contain information such as where to search for the database, the name of the database to connect to, and configuration properties. The exact syntax of a database connection URL is specified by your DBMS.

Java DB Database Connection URLs

The following is the database connection URL syntax for Java DB:
jdbc:derby:[subsubprotocol:][databaseName][;attribute=value]*
  • subsubprotocol specifies where Java DB should search for the database, either in a directory, in memory, in a class path, or in a JAR file. It is typically omitted.
  • databaseName is the name of the database to connect to.
  • attribute=value represents an optional, semicolon-separated list of attributes. These attributes enable you to instruct Java DB to perform various tasks, including the following:
    • Create the database specified in the connection URL.
    • Encrypt the database specified in the connection URL.
    • Specify directories to store logging and trace information.
    • Specify a user name and password to connect to the database.
See Java DB Developer's Guide and Java DB Reference Manual for more information.

MySQL Connector/J Database URL

The following is the database connection URL syntax for MySQL Connector/J:
jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
  • host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
  • database is the name of the database to connect to. If not specified, a connection is made with no default database.
  • failover is the name of a standby database (MySQL Connector/J supports failover).
  • propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.
See MySQL Reference Manual for more information.

Using a DataSource Object for a Connection

A DataSource object represents a particular DBMS or some other data source, such as a file. The following method, JDBCTutorialUtilities.getConnectionWithDataSource, creates a DataSource object, then creates a Connection object, which represents a database connection with the DataSource object:
  public Connection getConnectionWithDataSource(String dbmsName, String dbNameArg, String userName, String password, String serverName, int portNumber) throws SQLException {
    Connection conn = null;

    if (dbmsName.equals("mysql")) {
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds = null;
      ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      ds.setUser(userName);
      ds.setPassword(password);
      ds.setServerName(serverName);
      ds.setPortNumber(portNumber);
      conn = ds.getConnection();
    } else if (dbmsName.equals("derby")) {
      org.apache.derby.jdbc.EmbeddedDataSource ds = null;
      ds = new org.apache.derby.jdbc.EmbeddedDataSource();
      ds.setDatabaseName(dbNameArg);
      ds.setUser(userName);
      ds.setPassword(password);
      conn = ds.getConnection();
    }
    System.out.println("Connected to database");
    return conn;
  }
Each DBMS driver contains a class that implements the interface java.sql.DataSource. MySQL Connector/J implements it with the class com.mysql.jdbc.jdbc2.optional.MysqlDataSource. Java DB has several classes that can create DataSource objects including the following:
  • org.apache.derby.jdbc.EmbeddedDataSource: Use this class if Java DB is running in the same Java Virtual Machine as your application.
  • org.apache.derby.jdbc.ClientDriver: Use this class if your application access Java DB from an external server.
Unlike a DriverManager object, you can configure a DataSource object by setting any of its various properties, such as the database's server name and port number. Consequently, you do not have to code the driver name or the JDBC URL into your applications. This makes your application code more portable.
Typically, using a tool that comes with an application server, a system administrator creates and configures a DataSource object, then registers it with a naming service that uses the Java Naming and Directory Interface (JNDI) API. JNDI enables applications based on Java technology to store and retrieve named Java objects of any type. Consequently, a developer can use JNDI to retrieve the pre-configured DataSource object that the system administrator created.
For more information about developing applications with the DataSource class,

No comments:

Post a Comment