1.tomcat的config/server.xml中将以下代码写到 </Host>前:

<Context docBase="struts1" path="/struts1" reloadable="true" source="org.eclipse.jst.jee.server:struts1">     <!--struts1为工程名-->
<Resource
 name="jdbc/demoDS">     <!--name与web.xml中name要一致,其中demoDS还要与后文中java代码(javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/demoDS");部分一致-->
 scope="Shareable"
 type="javax.sql.DataSource"
 factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
 url="jdbc:mysql://localhost:3306/test"     <!--test为数据库名-->
 driverClassName ="com.mysql.jdbc.Driver"
 username="root"
 password="123456"
/>

2.web.xml中引入数据源(三个参数顺序不能变,否则编译不通过)

<resource-ref>    
       <res-ref-name>jdbc/demoDS</res-ref-name>    
       <res-type>javax.sql.DataSource</res-type>  
       <res-auth>Container</res-auth> 

</resource-ref>

3.写java代码连接

package util;
import java.sql.Connection;
public class Struts
 {
    protected javax.naming.Context ctx = new javax.naming.InitialContext();
    protected javax.sql.DataSource ds;
     protected Connection conn;
     public Struts() throws Exception
     {
         ds = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/demoDS");
         conn = ds.getConnection(); 
    }
 }

 

4.应用示例代码,写一个查询函数

 public List<String[]> search() throws Exception
       {
           List<String[]> result = new LinkedList<String[]>();
           String sql = "SELECT * FROM Stu_Course WHERE SNo='"
+ form.getCNo() +"'";
           PreparedStatement pstmt =  conn.prepareStatement(sql);
           ResultSet rs = pstmt.executeQuery(); 
          while(rs.next())
           {
               String[] row = new String[4];
               row[0] = rs.getString(1);
               row[1] = rs.getString(2);
               row[2] = String.valueOf(rs.getInt(3));
               row[3] = rs.getString(4);
               result.add(row);
           }
           rs.close();
           conn.close();
           return result;
       }

蛋疼的,以前弄过就忘,再用到就有蛋疼一遍,记下来。。。

 

 

        

posted on 2014-12-05 23:28  慧是永远  阅读(845)  评论(0编辑  收藏  举报