看你是哪个JSP容器,不同的容器配置方法不一样,不过连接代码都差不多String jndi = ""   //和配置文件的jndi名字相同
Context initCtx = new InitialContext();
DataSource ds = initCtx.lookup(jndi);
if (ds != null) 
    Connection conn = ds.getConnection();

解决方案 »

  1.   

    如上,但是这样的代码也只能在jsp,servelt这些在容器中运行的代码才能这样写,否则new InitialContext();是要配置参数的,或是必须有jndi.properties文件,比如使用main开启一个进程而不是在容器进程中运行
      

  2.   

    不同的数据库不一样啊,以mysql为例,首先要在server.xml中加入<Resource>元素,假如
     jdbc/BookDB为数据源
    <!-- configure DataSource. Add the following code into server.xml --><Context path="/bookstore" docBase="bookstore" debug="0"
    reloadable="true" >
      <Resource name="jdbc/BookDB"
                   auth="Container"
                   type="javax.sql.DataSource" />  <ResourceParams name="jdbc/BookDB">
        <parameter>
          <name>factory</name>
          <value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
        </parameter>    <!-- Maximum number of dB connections in pool. Make sure you
             configure your mysqld max_connections large enough to handle
             all of your db connections. Set to 0 for no limit.
             -->
        <parameter>
          <name>maxActive</name>
          <value>100</value>
        </parameter>    <!-- Maximum number of idle dB connections to retain in pool.
             Set to 0 for no limit.
             -->
        <parameter>
          <name>maxIdle</name>
          <value>30</value>
        </parameter>    <!-- Maximum time to wait for a dB connection to become available
             in ms, in this example 10 seconds. An Exception is thrown if
             this timeout is exceeded.  Set to -1 to wait indefinitely.
            Maximum time to wait for a dB connection to become available
             in ms, in this example 10 seconds. An Exception is thrown if
             this timeout is exceeded.  Set to -1 to wait indefinitely.
             -->
        <parameter>
          <name>maxWait</name>
          <value>10000</value>
        </parameter>    <!-- MySQL dB username and password for dB connections  -->
        <parameter>
         <name>username</name>
         <value>dbuser</value>
        </parameter>
        <parameter>
         <name>password</name>
         <value>1234</value>
        </parameter>    <!-- Class name for mm.mysql JDBC driver -->
        <parameter>
           <name>driverClassName</name>
           <value>com.mysql.jdbc.Driver</value>
        </parameter>    <!-- The JDBC connection url for connecting to your MySQL dB.
             The autoReconnect=true argument to the url makes sure that the
             mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
             connection.  mysqld by default closes idle connections after 8 hours.
             -->
        <parameter>
          <name>url</name>
          <value>jdbc:mysql://localhost:3306/BookDB?autoReconnect=true</value>
        </parameter>
      </ResourceParams></Context>
      

  3.   

    然后,再web.xml中加入<resource-ref>元素
    <resource-ref>
           <description>DB Connection</description>
           <res-ref-name>jdbc/BookDB</res-ref-name>
           <res-type>javax.sql.DataSource</res-type>
           <res-auth>Container</res-auth>
       </resource-ref>
      

  4.   

    JSP这样写:
    <!--首先导入一些必要的packages-->
    <%@ page import="java.io.*"%>
    <%@ page import="java.util.*"%>
    <%@ page import="java.sql.*"%>
    <%@ page import="javax.sql.*"%>
    <%@ page import="javax.naming.*"%>
    <%@ page import="com.mysql.jdbc.Connection"%>
    <!--设置中文输出-->
    <%@ page contentType="text/html; charset=GB2312" %>
    <html>
    <head>
      <title>DbJsp1.jsp</title>
    </head>
    <body>
    <%
    //以try开始
    try
    {
    java.sql.Connection con;
    Statement stmt;
    ResultSet rs;//建立数据库连接
    Context ctx = new InitialContext();
    DataSource ds =(DataSource)ctx.lookup("java:comp/env/jdbc/BookDB");
    con = ds.getConnection();
    //创建一个JDBC声明
    stmt = con.createStatement();
    //增加新记录
    stmt.executeUpdate("INSERT INTO books (id,name,title,price) VALUES ('999','Tom','Tomcat Bible',44.5)");
    //查询记录
    rs = stmt.executeQuery("SELECT id,name,title,price from books");
    //输出查询结果
    out.println("<table border=1 width=400>");
    while (rs.next())
    {
    String col1 = rs.getString(1);
    String col2 = rs.getString(2);
    String col3 = rs.getString(3);
    float col4 = rs.getFloat(4);//convert character encoding
    col1=new String(col1.getBytes("ISO-8859-1"),"GB2312");
    col2=new String(col2.getBytes("ISO-8859-1"),"GB2312");
    col3=new String(col3.getBytes("ISO-8859-1"),"GB2312");//打印所显示的数据
    out.println("<tr><td>"+col1+"</td><td>"+col2+"</td><td>"+col3+"</td><td>"+col4+"</td></tr>");
    }
    out.println("</table>");//删除新增加的记录
    stmt.executeUpdate("DELETE FROM books WHERE id='999'");//关闭数据库连结
    rs.close();
    stmt.close();
    con.close();
    }//捕获错误信息
    catch (Exception e) {out.println(e.getMessage());}%>
    </body>
    </html>