JDBC DataSource NoInitialContextException


General J2EE: JDBC DataSource NoInitialContextException

  1. JDBC DataSource NoInitialContextException (2 messages)

    I am trying to learn how to use datasources to get connections, and I am successful in doing this for the MysqlDataSource in this way: connection = mysqlDataSource.getConnection(); However, I want to try to retrieve the connection via a Context, and am unsuccessful in creating the initial association, like this: MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl ( "jdbc:mysql://" ); dataSource.setUser( stringUser ); dataSource.setPassword( stringPass ); // String stringDataSourceMYS = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"; Properties properties = new Properties(); properties.put( Context.INITIAL_CONTEXT_FACTORY, stringDataSourceMYS ); properties.put( Context.PROVIDER_URL , "jdbc:mysql://" ); // Context context = new InitialContext( properties ); context.bind( "jdbc/mySql" , dataSource ); It renders the following error: javax.naming.NoInitialContextException: Cannot instantiate class: com.mysql.jdbc.jdbc2.optional.MysqlDataSource [Root exception is java.lang.ClassCastException] I do not think this is a path issue (since it works w/o using the context bind). I do not know what I need to make it "bind" properly. Can anyone help with this? Thank You.
  2. hey George, using the Context, is a way to obtain the database Connection factory via JNDI, via the Context. ..the "stringDataSourceMYS", would point to the registered ConnectionFactory in the application Server, then create the DataSource.
  3. Thanks, Jeryl. I also noticed this: The properties of the Context did not show an appropriate provider url for the hosting of the datasource. I was avoiding an App server (for a blackbox demo), so I needed to create an RMI registry server, create the datasource (with its own URL), and bind the datasource to the context with the provider url of the RMI server: LocateRegistry.createRegistry( intPortRMI ); // MysqlDataSource mysDataSource = new MysqlDataSource(); mysDataSource.setUrl ( stringUrlMYS ); // setPort setServerName mysDataSource.setUser ( stringUser ); mysDataSource.setPassword ( stringPass ); DataSource dataSource = ( DataSource ) mysDataSource ; // Properties properties = new Properties(); properties.put( Context.INITIAL_CONTEXT_FACTORY, stringFactRmi ); properties.put( Context.PROVIDER_URL, stringUrlRmi ); // InitialContext context = new InitialContext( properties ); context.rebind( "anyLookupName" , mysDataSource );