Java Reference
In-Depth Information
You want to create a connection to a database from within a desktop Java application.
Solution 1
Use a JDBC Connection object to obtain the connection. Do this by creating a new
connection object, and then load the driver that you need to use for your particular
database vendor. Once the connection object is ready, call its getConnection()
method. The following code demonstrates how to obtain a connection to an Oracle or
Apache Derby database, depending on the specified driver.
public Connection getConnection() throws SQLException {
Connection conn = null;
String jdbcUrl;
if(driver.equals("derby")){
jdbcUrl = "jdbc:derby://" + this.hostname + ":" +
this.port + "/" + this.database;
} else {
jdbcUrl = "jdbc:oracle:thin:@" + this.hostname
+ ":" +
this.port + ":" + this.database;
}
System.out.println(jdbcUrl);
conn = DriverManager.getConnection(jdbcUrl, username,
password);
System.out.println("Successfully connected");
return conn;
}
The method portrayed in this example returns a Connection object that is ready
to be used for database access.
Solution 2
Use a DataSource to create a connection pool. The DataSource object must have
been properly implemented and deployed to an application server environment. After a
DataSource object has been implemented and deployed, it can be used by an applic-
Search WWH ::




Custom Search