tomcat配置数据源

来源:互联网 发布:怎么把照片上传到淘宝 编辑:程序博客网 时间:2024/06/11 06:32

1)在tomcat、lib加入数据库的jar包  ojdbc7 我的下载中有(这个是花了2积分下载了别人的)

2)在Tomcat的contex,xml中进行配置数据库

                                     //name 属性 自己写的名称

ex:<Resource name="jdbc/oracleds"
        author="Container"
        type="javax.sql.DataSource"
        maxActive="100"
        maxIdle="30"
        maxWait="10000"
        username="数据库用户名"
        password="数据库密码"
        driverClassName="oracle.jdbc.driver.OracleDriver"  

      // 这是我的url  自己的需要自己配置

      url="jdbc:oracle:thin:@211.88.5.178:1521/oracle11g" />

3)在项目中的web.xml中进行配置

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

4)测试可行性 

  这是在servlet中的部分代码

dbtest dbs=new dbtest();
        int i=    dbs.getAll();
        if(i==1){
            //请求转发
            //request.getRequestDispatcher("success.jsp").forward(request,response);
            //重定向
            response.sendRedirect("success.jsp");
        }else{
            
        }

 链接数据库代码:

public class dbtest {
    static Connection conn=null;
    ResultSet rs=null;
    Statement st=null;
    public static Connection conn(){
        try {      
            //初始化查找命名空间
            Context ctx = new InitialContext();  
            //参数java:/comp/env为固定路径   
            Context envContext = (Context)ctx.lookup("java:/comp/env");
            //参数为数据源和JNDI绑定的名字
            DataSource ds = (DataSource)envContext.lookup("jdbc/oracleds");
            conn = ds.getConnection();  
        } catch (NamingException e1) {     
            e1.printStackTrace();     
        } catch (SQLException e) {     
            e.printStackTrace();     
        }
        return conn;
    }  
    public  static Integer getAll() {
        int j=0;
        conn();
        String sql = "select t.*, t.rowid from WZNB_CORP_USER t where t.id between '357967' and '357968'";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            int col = rs.getMetaData().getColumnCount();
            System.out.println("============================");
            while (rs.next()) {
                for (int i = 1; i <= col; i++) {
                    System.out.print(rs.getString(i) + "\t");
                    
                 }
                System.out.println("");
            }
            j=1;
                System.out.println("============================");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return j;
    }
}



最后附录:

spring中的部分代码

 * spring 配置数据源的情况下是这样的
 *1.<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
 *2.<property name="jndiName">
  3.<value>java:comp/env/jdbc/oracleds</value>
  4.</property>

5. </bean>

原创粉丝点击