This section describes how to use ClientDataSource class to connect to Derby Network Server without JNDI.
Derby JDBC driver offers several DataSource classes. One of them is the org.apache.derby.jdbc.ClientDataSource class, which can be
used to create a connection to a Derby Network Server. ClientDataSource class can be used directly to create a connection without using
JNDI (Java Naming Directory Interface) as shown in the following sample program:
/**
* DerbyDataSource.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
import javax.sql.*;
import org.apache.derby.jdbc.*;
public class DerbyDataSource {
public static void main(String [] args) {
Connection con = null;
try {
// Setting up the DataSource object
ClientDataSource ds
= new org.apache.derby.jdbc.ClientDataSource();
ds.setServerName("localhost");
ds.setPortNumber(1527);
ds.setDatabaseName("TestDB");
// Getting a connection object
con = ds.getConnection();
// Running a query
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery(
"SELECT * FROM HY_Address");
System.out.println("List of Addresses: ");
while (res.next()) {
System.out.println(
" "+res.getInt("ID")
+ ", "+res.getString("StreetName")
+ ", "+res.getString("City"));
}
res.close();
sta.close();
con.close();
} catch (Exception e) {
System.err.println("Exception: "+e.getMessage());
}
}
}
The output I got from this program confirms that ClientDataSource class can be used directly without JNDI.
C:\>javac -cp .;\local\javadb\lib\derbyclient.jar DerbyDataSource.java
C:\>java -cp .;\local\javadb\lib\derbyclient.jar DerbyDataSource
List of Addresses:
1, 5 Baker Road, Bellevue
2, 25 Bay St., Hull
3, 251 Main St., W. York