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

    How to locate a DataSource in an EJB

    luckystar_007

      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

          Yes.

          Regards,
          Adrian

          • 2. Re: How to locate a DataSource in an EJB
            laz777

            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;
            }
            }