JNDI配置

tomcat/con/contert.xml­

<Resource name="jdbc/books" auth="Container" type="javax.sql.DataSource"­

maxActive="0" maxIdle="0" maxWait="-1" username="sa" password="000ooo"­

driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"­

url="jdbc:sqlserver://localhost:1433;DatabaseName=bookstore"­

/>­

项目里的web/xml­

<resource-ref>­

  <description>E-Books DataSource</description>­

  <res-ref-name>jdbc/books</res-ref-name>­

  <res-type>javax.sql.DataSource</res-type>­

  <res-auth>Container</res-auth>­

</resource-ref>­

 

 /**
  * get connection from jndi resource
  * @param jndiName
  * @return connection
  */
 public static Connection getConnection(String jndiName){
  Connection con = null;
  try {
   Context ctx = new InitialContext();
   DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/books");
   con = ds.getConnection();
  } catch (NamingException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return con;
 }

 

///db-config.properties

driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=bookstore
username=sa
password=sa
maxActive=100
maxIdle=30

 

 

 public static Connection getConnection(Object obj){
  System.out.println("method for properties file");
  Connection con = null;
  //get properties file stream
  Properties properties = new Properties();
  CommDBConnector cdbc = new CommDBConnector();
  InputStream ips = cdbc.getClass().getResourceAsStream("/db-config.properties");
  try {
   properties.load(ips);
   
   //get database connection configuration
   String driver = properties.getProperty("driverClassName");
   String url = properties.getProperty("url");
   String username = properties.getProperty("username");
   String password = properties.getProperty("password");
   int maxActive = Integer.parseInt(properties.getProperty("maxActive"));
   int maxIdle = Integer.parseInt(properties.getProperty("maxIdle"));
   
   BasicDataSource bds = new BasicDataSource();
   bds.setDriverClassName(driver);
   bds.setUrl(url);
   bds.setUsername(username);
   bds.setPassword(password);
   bds.setMaxActive(100);
   bds.setMaxIdle(30);
   con = bds.getConnection();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return con;
 }
 public static Connection getConnection(String a,String b){
  System.out.println("method for data source factory");
  Connection con = null;
  Properties properties = new Properties();
  CommDBConnector cdbc = new CommDBConnector();
  InputStream ips = cdbc.getClass().getResourceAsStream("/db-config.properties");
  try {
   properties.load(ips);
   DataSource ds = BasicDataSourceFactory.createDataSource(properties);
   con  = ds.getConnection();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return con;
 }

你可能感兴趣的:(JNDI)