Consultor Eletrônico



Kbase 21459: JDBC -- Sample Client Code To Look Up a DataSource
Autor   Progress Software Corporation - Progress
Acesso   Público
Publicação   10/16/2008
Status: Unverified

GOAL:

How can a client request a connection after a DataSource is registered with LDAP server.

FIX:

Typically, a client program does not have to execute the bind() or rebind() methods to bind a DataSource. A client program does a lookup() on the DataSource and requests a connection. The DataSource class contains a getConnection() method which returns a connection object. Once it has the connection object, the client program proceeds as usual.

import javax.naming.*;
import javax.naming.directory.*;
import java.sql.*;
import java.util.Hashtable;
import com.progress.sql.jdbcx.datasource.*;

class MLookup {
public static void main(String[] args) {
// Set up the environment for creating the initial context
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389");

try {
// Create the initial context
DirContext ctx = new InitialDirContext(env);

// Lookup the DataSource
JdbcProgressDataSource ds = (JdbcProgressDataSource)ctx.lookup("cn=mydb,ou=Databases,o=progress.com");
// Request a database connection
Connection con = ds.getConnection();
PreparedStatement pst = con.prepareStatement("select name from pub.customer",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
String s = rs.getString(1);
System.out.println("Name: " + s);
}
rs.close();
// Close the connection
con.close();
// Close the context when we're done
ctx.close();
}
catch (SQLException ex) {
System.out.println("SQL Exception received");
}
catch (NamingException e) {
System.out.println("Operation failed: " + e);
}
}
)