×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Nhan Tran
Added: Aug 7, 2021 1:04 PM
Views: 3669
Tags: no tags
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package Utils;
  7.  
  8. import java.sql.Connection;
  9. import java.sql.SQLException;
  10. import javax.naming.Context;
  11. import javax.naming.InitialContext;
  12. import javax.naming.NamingException;
  13. import javax.sql.DataSource;
  14.  
  15. /**
  16.  *
  17.  * @author TranViNhan
  18.  */
  19. public class DBContext {
  20.  
  21.     private DBContext() {
  22.         throw new IllegalStateException("Utility class");
  23.     }
  24.  
  25.     //viết hàm lấy connection tới ms sql
  26.     /**
  27.      *
  28.      * @return @throws SQLException
  29.      * @throws NamingException
  30.      */
  31.     public static Connection makeConnection() throws SQLException, NamingException {
  32.         //khoi tao bien connection
  33.         Connection cnn;
  34.         //khoi tao bien Context
  35.         Context currentContext = new InitialContext();
  36.         //tim context cua tomcat
  37.         Context tomcatContext = (Context) currentContext.lookup("java:comp/env");
  38.         //tim datasource da luu trong context
  39.         DataSource ds = (DataSource) tomcatContext.lookup("HOTEL_DB");
  40.         cnn = ds.getConnection();
  41.  
  42.         return cnn;
  43.  
  44.     }
  45. }
  46.