Urget ...Can I use Dataource in servlets

Discussions

Web tier: servlets, JSP, Web frameworks: Urget ...Can I use Dataource in servlets

  1. Urget ...Can I use Dataource in servlets (4 messages)

    Hello!!
    I don't want to use System DSN to get connection with database.
    Instead of it I want to get the datasource through my code and get the connection thr' that datasource in a servlet.
    Can anyone help me??
  2. Of course you can lookup up the datasource directly from your servlet. This is always better than taking a raw connection (except in case of long running processes, where a raw connection is preferred).
    You can do a lookup as:

    Context context = new InitialContext();
    javax.sql.DataSource ds = (javax.sql.DataSource)context.lookup("DatasourceName");
    Connection con = ds.getConnection();
    Catch the NamingException and SQLException
  3. ya u can use DataSource in servlets create a Data Source in
    DataSource.xml or ur vendor Specfic way and create a initial context in Servlet and use the connection u will also get Connection Poooling Effect if ur using App Server (j2ee 1.3or1.2)Compliant.This is JSP Example:

    <%@ page language="java" import ="java.sql.Connection,javax.sql.DataSource,javax.naming.*" %>

    <%
    java.sql.Connection objConn=null;
    try {

    Context ctx = new InitialContext();

    javax.sql.DataSource dsDept = (javax.sql.DataSource) ctx.lookup("jdbc/MdoDataSource");
    objConn=dsDept.getConnection();
    objConn.setAutoCommit(false);

        }
    catch (Exception e)
    {
    System.err.println("Could not locate datasource! Reason:");
    e.printStackTrace();
    throw e;
    }

    %>
    Rgds
    Sharma
  4. where will I get this javax.sql package???

    thanks in advance to ur replies....
  5. If u download JDK1.3.3 or 1.4 you will get javax.sql package