zoukankan      html  css  js  c++  java
  • Java通过JNDI获取数据源

    1. package common;
    2. import java.sql.Connection;
    3. import java.sql.SQLException;
    4. import javax.naming.Context;
    5. import javax.naming.InitialContext;
    6. import javax.naming.NamingException;
    7. import javax.sql.DataSource;
    8. /**
    9.  * 通过JNDI获取数据源
    10.  * @author 周尚武
    11.  * 时间:2008年12月8日22:37:09
    12.  */
    13. public class DBConnection {
    14.     /**
    15.      * 通过JNDI获取数据源在获取连接对象
    16.      * @return Connection con
    17.      */
    18.     public static Connection getCon(){      
    19.         Connection con = null;
    20.         try {
    21.             Context ic = new InitialContext();
    22.             DataSource source = (DataSource)ic.lookup("java:comp/env/jdbc/books");          
    23.             con = source.getConnection();       
    24.         } catch (NamingException e) {
    25.             System.out.println("数据源没找到!");
    26.             e.printStackTrace();
    27.         } catch (SQLException e) {
    28.             System.out.println("获取数连接对象失败!");
    29.             e.printStackTrace();
    30.         }
    31.         return con;
    32.     }
    33. }

    JNDI的配置:

    1.context.xml文件的配置:

    1. <Resource name="jdbc/books" 
    2.        auth="Container" type="javax.sql.DataSource"  maxActive="100"  
    3.        maxIdle="30" maxWait="10000"   username="sa"   password="123" 
    4.        driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
    5.        url="jdbc:sqlserver://localhost:1433;databasename=books"/>

    2.web.xml文件的配置:

    1. <resource-ref>
    2.     <res-ref-name> jdbc/books </res-ref-name>
    3.     <res-type> javax.sql.DataSource </res-type>
    4.     <res-auth> Container </res-auth>
    5. </resource-ref>

    3.添加数据库驱动文件:

    通过数据源访问数据库,由于数据源由Tomcat 维护,所有必须把JDBC驱动程序复制到Tomcat的common/lib目录下。

     

    注意:如果要是用的MyEclipce自带的Tomcat可以从Configure中

    选中paths-----》在点击Add JAR/ZIP-----》加载相应的JDBC驱动

  • 相关阅读:
    ./sample_mnist: error while loading shared libraries: libnvinfer.so.4: cannot open shared object file: No such file or directory
    Unable to correct problems, you have held broken packages
    `TypeError: torch.mm received an invalid combination of arguments
    error: ‘module’ object has no attribute ‘_rebuild_tensor_v2’
    cafee编译错误几个总结
    对yolo与fasterrcnn anchors的理解
    msf提权常用命令
    解析漏洞总结
    webshell方法总结
    XSS之会话劫持
  • 原文地址:https://www.cnblogs.com/eggbucket/p/2343971.html
Copyright © 2011-2022 走看看