2 Replies Latest reply on Feb 27, 2002 6:59 PM by Todd Marshall

    How to locate a DataSource in an EJB

    jian gao Newbie

      After configuring a DataSource,how should I write code to get database connection in an EJB?
      Shall I use JNDI? Thanks!

        • 1. Re: How to locate a DataSource in an EJB
          Adrian Brock Master

          Yes.

          Regards,
          Adrian

          • 2. Re: How to locate a DataSource in an EJB
            Todd Marshall Newbie

            Yes, you want to use JNDI.

            Here is an example in a helper class I wrote so I could have easy access in my JSPs to the same datasource I was using in my beans.


            import java.sql.*;
            import javax.sql.*;
            import javax.naming.*;
            import javax.rmi.*;


            public class DBConnection
            {

            static public Connection getConnection()
            {
            Connection dbConn = null;
            try
            {

            // get database connection from jboss
            Context initialContext = new InitialContext();
            DataSource ds= (DataSource) initialContext.lookup("java:/DefaultDS");
            dbConn = ds.getConnection();

            }
            catch (NamingException ne)
            {
            System.out.println("Naming Exception: " + ne);
            }
            catch (SQLException se)
            {
            System.out.println("SQL Exception: " + se);
            }

            return dbConn;
            }
            }