Is it possible to connect database using session bean

Dear all,
Is it possible to connect database using session bean without using entity beans like cmp,bmp.
if ur answer is yes, then pls tell me where to put the select statement and transaction attribute like(6 types).
if u have sample code, then it is good for me.
Hope I will get answer.

Sure it is.
Try something like this (and maybe get a book on JDBC):
String name;
try {
     InitialContext ic = new InitialContext();
     DataSource ds = (DataSource) ic.lookup(Constants.MY_DATASOURCE);
     Connection connection = ds.getConnection();
     String sql = "SELECT * FROM TABLE";
     PreparedStatement statement = connection.prepareStatement(sql);
     ResultSet rs = statement.executeQuery();
     while (rs.next()) {
          name = rs.getString("NAME");
     if (rs != null)
          rs.close();
     if (statement != null)
          statement.close();
     if (connection != null)
          connection.close();
catch (NamingException e) {
     // Can't get JDBC datasource
     // ... do something with this exception
catch (SQLException e) {
     // SQL exception from getter
     // .... do seomthing with this one too
}

Similar Messages

  • Can I connect with Database using Session Bean

    Hi,
    I am new to EJB. I have small doubt.
    can I connect with Database using Session Bean.
    Regards,
    Murali.

    Double post of http://forum.java.sun.com/thread.jspa?threadID=687239&tstart=0

  • Connect database using ext javascript or applescipt in indesign

    Hi,
    I need to connect oracle database using extended javascript or apple script in indesign. Can somebody help by giving any suggestion. Or is there any possibility to connect database using the two scripting methods.
    It  is really urgent.
    Thanks
    Karthik B

    ExtendScript has a Socket object prototype you can use to e.g. connect to the internet. Calling a web service would probably be more elegant than addressing the database directly. Socket is fairly low-level, though. If you need something easier, you could always try out http://extendables.org/docs/packages/http/doc/readme.html
    I seem to recall some InDesign plug-ins you could buy that allow you to connect to a database directly, but you'd have to google that yourself.

  • How to connect database using coding in trigger in forms

    Oracle forms6i
    Hai All
    Is there any possiblity to connect database using coding.
    For example when we open a form and we use some button and write some coding and when we execute a small will appear and we give username,connection identifier and database name.
    Is it any possible there when we create a button and in that button we write coding our database name,connectionid and user and when we exe it will internally connect database Pls tell me..
    Regards
    Srikkanth.M

    use LOGON Procedure
    PROCEDURE LOGON
      (username  VARCHAR2,
       password  VARCHAR2);
    logon('scott','tiger@orcl');Mr.Srikkanth.M if u dont close ur old questions dont expect others to answer ur question everytime......so plz remember if u think the person's answer is helpful or correct mark it accordingly
    Thanks :)
    Baig
    [My Oracle Blog|http://baigsorcl.blogspot.com/]

  • Using Session Beans on a read only database

    Hi,
    i am working on a weblogic 6.1 server and have to access a read only database
    using session beans. The transaction attributes of all session beans (we are using
    no entity beans) are set to NOT_SUPPORTED but every time a method is accessed
    an error message is thrown
    BEGIN TRANS in read only database .....
    Is there a way to avoid this?
    Regards
    Edmund

    I guess it is NotSupported. If not try Never.
    --Jay   
    www.architectslobby.org
    An exclusive community for Enterprise Architects

  • General Design With Database and Session Bean Question

    I have an application I am developing where users connect to individual databases located on a server. When they login an admin table is accessed which shows what databases they have permissions to. I am then storing the connection to the database in a backing bean. Hoping to use this connection throughout the session. Is this a good practice to have a users connection left open over the session? I can't create a database pool for each individual database and each user for that database.
    If I can store that database connection in a session bean. How do I access that connection from another bean. Or from another java class? I am using Glassfish for my application server with JSF1.2. I have looked at resource injection but have not had any luck with sharing the session bean information.
    Sorry if this is a trivial question. I have been a Java developer for years. But just starting developing webapps using JSF.
    Thanks

    JuCobb2 wrote:
    I am then storing the connection to the database in a backing bean. Hoping to use this connection throughout the session. Is this a good practice to have a users connection left open over the session? No it is not. Why should you do so? Always keep the lifetime of connection, statement and resultset as short as possible.

  • Help Connecting A Stateless Session Bean To MySQL Database

    Hi, I'm trying to connect a simple stateless session bean that has been
    deployed using the admin console to a MySQL database that has been
    set up and pinged using the JDBC Resources/Connection Pools part of the
    admin console.
    When I attempt to connect to the database using the session bean I get the
    following error message:
    Exception in thread "main" java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
         java.rmi.RemoteException: ; nested exception is:
         java.sql.SQLException: No database selected
         at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:161)
         at javax.rmi.CORBA.Util.mapSystemException(Unknown Source)
         at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:142)
         at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(Unknown Source)
         at DBDynamicStub.testDatabase(_DB_DynamicStub.java)
         at DBClient.main(DBClient.java:9)
    Caused by: java.rmi.RemoteException: ; nested exception is:
         java.sql.SQLException: No database selected
         at com.sun.ejb.containers.InvocationHandlerUtil.throwRemoteException(InvocationHandlerUtil.java:96)
         at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:141)
         at $Proxy26.testDatabase(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:123)
         at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatchToServant(CorbaServerRequestDispatcherImpl.java:648)
         at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatch(CorbaServerRequestDispatcherImpl.java:192)
         at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequestRequest(CorbaMessageMediatorImpl.java:1709)
         at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1569)
         at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleInput(CorbaMessageMediatorImpl.java:951)
         at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:181)
         at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:721)
         at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.dispatch(SocketOrChannelConnectionImpl.java:469)
         at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.doWork(SocketOrChannelConnectionImpl.java:1258)
         at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:409)
    Caused by: java.sql.SQLException: No database selected
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2851)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2379)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2306)
         at com.mysql.jdbc.Statement.executeQuery(Statement.java:1192)
         at DBBean.testDatabase(DBBean.java:45)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:585)
         at com.sun.enterprise.security.SecurityUtil$2.run(SecurityUtil.java:153)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.enterprise.security.application.EJBSecurityManager.doAsPrivileged(EJBSecurityManager.java:950)
         at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:158)
    Obviously this means that the bean can't connect to the database but I am
    unsure why this is. When I set up the database using the admin console
    I set the the jndi name to jdbc/test and I've tried using the following look up
    code to find the database that is referenced by the JNDI name:
    Context context = new javax.naming.InitialContext();
              DataSource ds = (DataSource) context.lookup("jdbc/test");
    and also
    Context context = new javax.naming.InitialContext();
    DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/test");
    Neither of these methods work.
    When I look at the JNDI Tree Browsing window which is available from the
    admin console there is no mention of the database at all, there are four
    items in the three, they are:
    UserTransaction
    ->jdbc
    ->ejb
    DBBean
    Do I need to add a JNDI reference somewhere in order for the bean to locate
    the database? I thought that when I created the database in the admin
    console and specified a JNDI name this would be all that's required in order
    for beans to locate the database, obviously not.
    If anyone can offer any advice at all I would be very very grateful.
    Ian

    stmt.execute("use YOUR_DATABASE_NAME");
    // then your db queries.This approach works for me.
    It also works to specify the database in the query like this:
    InitialContext initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup("jdbc/myDB");
    Connection conn = ds.getConnection();
    try {
           Statement statement  = conn.createStatement();
           ResultSet rs = statement.executeQuery("select * from myDB.news");
           ...As you can see I added myDB. to the query.
    But why is this necessary?
    If I use DriverManager instead, this is NOT necessary. Like this:
    Connection connection = null;
    try {
           Class.forName("com.mysql.jdbc.Driver");
           connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB", "username", "password");
           Statement statement = connection.createStatement();
           ResultSet rs = statement.executeQuery("select * from news");
           ...Why do I not have to run the query statement.execute("use YOUR_DATABASE_NAME"); or specify the database name in the query statement.executeQuery("select * from myDB.news"); when I use DriverManager to obtain a Connection when I have to do that when using a DataSource?
    It don't seem very efficient to have to run the extra query ( use db-name ) before I run any other query in my application.

  • How to Connect Database Using Script?

    Hi all,
                    Am using Adobe InDesign CS3. Is there any way to connect database from Adobe InDesign CS3 Scripting (Javascript)? Thanks in advance.
    Regards,
    Mohan

    I don't know javascript so I can't help with that part.
    The system plug in you need is from Actual Technologies : http://www.actualtechnologies.com/ The setup for that is detailed in their instructions. You will probably want to set it up for system-wide access, not by user. I found system-wide access more reliable, fwiw.
    For Applescript I send a command through the Terminal/command line that returns the data from the query.
    Here is Applescript:
    set query to "YOUR DB QUERY"
    set results to (do shell script "echo \"" & query & "\" | iodbctest \"dsn=" & dsn & ";uid=" & uid & ";pwd=" & pwd & "\" | awk '{ if (match($0,\"SQL>\")) {k++; if (k==1) next; if (k==2) exit; } if (k==1) print; }'")
    You can probably do something similar in Javascript. You'll have to parse out the text data returned then. I think there may be plug-ins for InDesign that can directly connect to a database (?). Or some plug-ins like inData can take their data passed from a script as well.
    Chris

  • Example of using session bean with webservices

    Hello,
    I am working with netbeans 5.5 (with JAX-WS 2.0 library) and using Tomcat.
    I have created webservices and everything is working well so far. However, each webservice is making a connection to my database.
    I would like to use a session bean so that I make the connection only once (at the begining of the client session for example) and store it into my session bean.
    I am a newbie in those things, I search on the Web and on this forum some code examples. The only thing I have found is this article http://weblogs.java.net/blog/ramapulavarthi/archive/2006/06/maintaining_ses.html
    When I tried this, the session doesn't seem to work at all : I get the same result (counter=1) twice.
    Does anybody have a complete example of how to use a session with webservices please?
    Thanks a lot!

    Sorry, I was not very clear in my last message.
    I need all my webservices to share the same bean during one user session.
    Then, if a page calls 2 different web services, only 1 database connection is made instead of 2. And if the user opens other pages which call other webservices, they will use the connection kept into the session bean.
    Anyway, I tried to do like it is said in your website but I can not build my project. I have an error : java.lang.LinkageError: JAXB 2.0 API is being loaded from the bootstrap classloader, but this RI (from jar:file:/C:/.../build/web/WEB-INF/lib/jaxb-impl.jar!/com/sun/xml/bind/v2/model/impl/ModelBuilder.class) needs 2.1 API. Use the endorsed directory mechanism to place jaxb-api.jar in the bootstrap classloader. I do not understand because I have downloaded the jax-ws 2.1.1 api and no other libraries are imported in my project. :-(
    I wonder if it is not related to netbeans...

  • How can i design a EJB application using session Beans?

    Hello,
    I am designing a Find application using EJB. Here a user is prompted a search page, where he can enter the search criteria's. Then on click of submit, the query is formed at the server side depending on what criteria's were selected. Then a jdbc query is performed and the results are returned back to the user. Here no session is maintained for the users. Can anyone suggest me how to design this application using EJB. Should i use entity beans for this or session beans will suffice? Should the jdbc query be performed in the bean itself or should it be outside in a helper class? Please kindlu suggest me the design for this application...
    Regards,
    Subbu

    Hi,
    First of all, I'm unable to figure out why you need to use EJB for this scenario. You can write a helper class to frame and execute the query.
    If you really want to use EJB, then I suggest you use a stateless Session Bean with transaction attribute as TX_NOT_SUPPORTED. From the session bean, you can call the helper class. But, by avoiding the session bean, you can eliminate remote calls, thus improving your performance. Also, check if the database & the db driver you are using supports sql caching.
    Regards,
    Raj.

  • Problem with connecting from Netweaver Session Bean to SAP R/3

    Hi,
    i just want a connection to RFC in SAP R/3 and with help of sap ("Proxy generation" etc) and wizard in NWDS i get the rfc. Now i want to connect and use it (like in handbook) but: Every time i create and use jcoclient.connect() system gets an error like:
    "Class File Editor
    Source not found
    The jar file jrfc.jar has no source attachment."
    I have add all files that are used to "Used DCs" or bind library into projekt as "Third party library", but the error is still there.
    Any idea? Do i have to make something else? Some failure made?
    thx
    Here is text for connection:
    Created on 26.06.2008
    To change the template for this generated file go to
    Window>Preferences>Java>Code Generation>Code and Comments
    package com.XXXXXXXXXXXXXXXXX;
    import com.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX;
    import com.sap.aii.proxy.framework.core.ApplicationFaultException;
    import com.sap.aii.proxy.framework.core.SystemFaultException;
    import com.sap.mw.jco.JCO;
    @author XXXXX
    To change the template for this generated type comment go to
    Window>Preferences>Java>Code Generation>Code and Comments
    public class MyMainClass extends Object
         public static void main(String[] args)
              throws ApplicationFaultException, SystemFaultException
              JCO.Client jcoclient =
                   JCO.createClient(
                        "XXX", //Client
                        "XXX", //User
                        "XXX", //Password
                        "XXX", //Language
                        "XXX", //Server
                        "XXX", //System
                        "XXX"); //Group
              jcoclient.connect();
              jcoclient.disconnect();
    Edited by: Torsten on Aug 27, 2008 10:43 AM
    Where can we download SAP NW7.0 (2004s) as Java Trial for testing? We only find ABAP Trial... Link? thx

    So we tested some things that are described in the SDN or by SAP with Connectors.
    We tested JCO version 2.0.12, 2.1.18 and 3.0 in J2EE Projects in netweaver and in Eclipse (Standalone).
    For version 2.0.12 there is a failure that this version is not compatible with the other things in netweaver.
    This version is for standalone and integrated sytems.
    For version 2.1.18 is only described as standalone and so failure happened in netweaver that other classes are coruppted or missed. The internal test in "content administrator" (Ping and Test) do not work and had the same error.
    For version 3.0 (that displace the other two versions) there is many to do in  settings and coding that we do not have tested yet because project is not that small to write it for JCO 3.0 only for testing. When we only displaced files in netweaver the server do not start any more.
    So:
    Is there a way to call R/3 from session bean and 1. create an JCO client or 2. add a client to the "standard" pool of netweaver to use it?
    Any ideas? help? links?
    Project have to be complete in september...
    Our combi is SAP Netweaver 2004 SP21 on Windows XP SP2 / Server 2003 Standard SP1 with JVM 1.4.2_16... need of any more info?
    thx

  • Security problem when trying to connect a CMP Session Bean deployed on J2EE

    I am working through Wrox�s book Professional java Mobile Programming and trying to set up the Mobile Positioning project. The book has instructions for Ericson MPS-SDK 3.0 but the only version available now is the 5.0 and these instructions are no longer valid. I have built the application with the Studio 4 IDE and deployed it on an instance of the J2EE reference Implementation and this seems to work fine. However I have built a CMP session bean which should connect to the Ericsson Emulator running on their supplied Eserver and this connection is failing with a security problem. Following is a snippet of the code I have used to instantiate the connection.
    ConnectionFactory con = null;
    con = new ConnectionFactory(true);
    The code compiles with out errors but when I try to test it I get the following error
    java.security.AccessControlException: access denied (java.util.PropertyPermission sun.net.inetaddr.ttl write)
    Any Hints or suggestions would be appreciated.
    Thanks

    Oops!! I meant Session Bean NOT CMP Session Bean

  • ClassCastException while using session bean in OC4J

    I am facing the same problem while deploying a stateless session bean in Oracle 9i AS 1.0.2.2.1. The details are given below.
    The following code snippet is used in the client to prepare for the lookup:
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.evermind.server.rmi.RMIInitialContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "welcome");
    //the following line can also have the actual machine name instead of "localhost"
    env.put(Context.PROVIDER_URL, "ormi://localhost:23893/myejbs");
    Context ctx = new InitialContext(env);
    System.out.println("Getting Home....");
    Object obj=ctx.lookup("Grouping");
    System.out.println("Home Object Is : "+obj);
    GroupingHome groupingHome = (GroupingHome)obj;
    System.out.println("Got Home");
    Grouping grouping = groupingHome.create( );
    graphs=grouping.<mehtods>();
    I've edited the config/server.xml file to have the following line:
    <application name="myejbs" path="C:\oracle\ora102\j2ee\home\applications\classes\myejbs" auto-start="true" />
    which points to the directory where the class files reside
    I've also change the port in the config/rmi.xml file to 23893.
    Now... the problem that I am facing is - while I am running a client from outside the server JVM i.e standalone client... which uses the Grouping interfaces, it works fine. giving me the desired result. But the moment I place the code in a service client deployed in the server or a jsp, I get a ClassCastException for GroupingHome whereas the SOP that I have given after lookup shows that I have found - "Grouping EJBHome". The funny thisng is that bith the working client and the JSP are using sme set of interface class files - Grouping.class (Remote) and GroupingHome.class.
    Where am I going wrong?? If anybody knows, or Giri has found an answer to his query... please post a reply.
    Thanks.
    PS: I've tried new InitialContext(); solution but it didn't work. I have also narrowed the home object with javax.rmi.PortableRemoteObject.narrow(obj,GroupingHome.class) but to no avail :(.

    Hi Gauarv,
    Did you not see my reply in the following post?
    Re: 502 service temporarily unavailable
    If I'm not mistaken, this is exactly the same question as you asked
    there.
    By the way, is there some reason you are still using OC4J version
    1.0.2.2? Is there something stopping you from upgrading to the later
    versions (9.0.2 and 9.0.3)?
    Good Luck,
    Avi.

  • Issue with Webservice Creation using Session Beans.

    Hi All,
    I want to expose my Session beans as webservice.
    I'm using Weblogic Application Server.
    When I do the modeling using JDeveloper, I'm unable to convert the Session bean to webservice.
    Any information on this is highly appreciable.
    Thanks & Regards,
    Kumar Madhavan.

    I can't give you much of a walk through, as I have just started it myself, but I'm using a universal unique identifier to represent each client. Whenever a client posts data from a jsp or applet the uuid is also sent. I use POST to pass all my parameters. If the server hasen't received data in say 5 minutes from the client then it is assumed the client went offline. Its working for me so far.
    COn

  • Using session bean in JSP

    Dear All
    I write a BorrowList session bean and tested OK in console mode. I can't use it in the JSP, Dose any body tell me How can I create this bean in the JSP and when should I place the bean classes(Home, Bean and Remote).
    I'm now using the BEA Weblogic 7.0
    I'm appreicate if anybody can help me.
    Best Regards
    YU

    U may be used the code similar to following :
    Context context = new InitialContext.();
    Object obj = (Object)context.lookup("Your JNDI name");
    YourHome home = (YourHome)obj.portableRemoteObject.narrow(obj,
    YourHome.class);
    YourRemote remote = home.create();
    System.out.println("your Business methods : "+remote.businessMethod1());
    Put this code or whatever code used in ur console client in JSP and invoke the businessMethods using remote object.
    I worked with BEAWeblogic 5.1, I think similar case may be there with BEA Weblogic7 also.
    First, make a jar file with ome.Remote and Bean by using the deploymenttool, then compile with ejb compiler, the new Jar is the complete deployable file. Take this file and register in weblogic.properties file that is specify the path of the Jar file in the weblogic.properties file. and put the JSP in public-html directory and start the server. if the bean is deployed successfully, open JSP file in a browser then it will work.... if the bean is not deployed you won't get any result.
    I can say, just placing the initialContext part of code on the JSP and running the JSP. I think, this may helps u...
    Ramana

Maybe you are looking for