This section describes how to create connection objects with the DataSource class.
It is recommended now that connection objects are created by the DataSource implementation class,
com.mysql.jdbc.jdbc2.optional.MysqlDataSource.
Here is a sample program that creates a connection object using the DataSource class without using JNDI services:
/**
* MySqlDataSource.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
import javax.sql.*;
public class MySqlDataSource {
public static void main(String [] args) {
Connection con = null;
try {
// Setting up the DataSource object
com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds
= new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
ds.setServerName("localhost");
ds.setPortNumber(3306);
ds.setDatabaseName("HerongDB");
ds.setUser("Herong");
ds.setPassword("TopSecret");
// Getting a connection object
con = ds.getConnection();
// Getting database info
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server name: "
+ meta.getDatabaseProductName());
System.out.println("Server version: "
+ meta.getDatabaseProductVersion());
// Closing the connection
con.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}
}
The output confirms that I got a good connection. Remember
to include mysql-connector-java-5.0.7-bin.jar in the classpath for compilation and execution:
C:\>javac -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar
MySqlDataSource.java
C:\>java -cp .;\local\lib\mysql-connector-java-5.0.7-bin.jar
MySqlDataSource
Server name: MySQL
Server version: 5.0.45-community-nt