To connect database with Microsoft SQL 2000 and Tomcat 6 via JNDI Datasource.
-Â Requirement:
Like the article? Be sure to subscribe to our RSS feed and follow us on Twitter to stay up on recent content.
-Â Edit contex.xml + web.xml
context.xml in tomcat_Home/conf/context.xml and web.xml in your WEB-INF of your web application:
- Edit your server contex.xml:
Find <Context> </Context> tag, in tag, add example:
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" Â Â Â Â Â Â Â Â Â Â maxActive="100" maxIdle="30" maxWait="10000" Â Â Â Â Â Â Â Â Â Â username="sa" password="sa" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" Â Â Â Â Â Â Â Â Â Â url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs" />
- Edit your server web-inf/web.xml (in your WEB-INF of web application)
Find <web-app></web-app> tag, in tag, add example:
<resource-ref> Â Â <description>DB Connection</description> Â Â <res-ref-name>jdbc/TestDB</res-ref-name> Â Â <res-type>javax.sql.DataSource</res-type> Â Â <res-auth>Container</res-auth> </resource-ref>
-Â Connect example:
Here is example JSP to use JNDI context:
<%@  page  contentType="text/html;charset=UTF-8" %> Â
<%@  page  import="java.sql.*" %>
<%@  page  import="javax.sql.*" %>
<%@  page  import="javax.naming.*" %>
<HTML>
<HEAD>
<TITLE>JSP example</TITLE>
</HEAD>
<BODY>
  <%
    out.println("<h1>Hello,test JNDI ! </h1>");
  %>
  <%
    Context ctx = new InitialContext(); Â
    Context envctx = (Context) ctx.lookup("java:comp/env");Â
    DataSource ds = (DataSource) envctx.lookup("jdbc/TestDB"); Â
    Connection conn=ds.getConnection(); Â
    Statement st=conn.createStatement();
    String  sql="select  *  from  jobs"; Â
    ResultSet  rs=st.executeQuery(sql);Â
    while(rs.next())  {
  %> Â
       String 1:<%=rs.getString(1) %> Â
       String 2:<%=rs.getString(2) %>Â
       <br>
  <%
   }
  %> Â
  <%out.print("Here is just JNDI datasource mssql2k + tomcat example");%>Â
  <%
   rs.close();Â
   st.close(); Â
   conn.close(); Â
  %>
</BODY>
</HTML>


Great! Thanks a lot