1. 程式人生 > >JNDI和JDBC的區別及使用

JNDI和JDBC的區別及使用

tint otf sel cal man found 行數 存儲過程 close

JDBC(Java Database Connectivity)是由數據庫中間服務商提供的,用於連接數據庫的Java API。一組類和接口(對接數據庫)。

JNDI(Java Name Directory Interface)是為應用服務器(Tomcat)管理資源所設置的目錄樣式的唯一標識。(數據庫、網頁、文檔等)


JDBC配置使用:

  •  // 第一步: 首先註冊驅動, 驅動一般只會註冊一次
    try {
           Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
    // 第二步:建立連接 Connect, 設置url ,用戶名, 密碼
       // url格式:JDBC:子協議:子名稱//主機名:端口/數據庫名?屬性名=屬性值&…
       // 註意的是url中一定不要加多余的空格,否則會出錯, useSSL=false是為了解決身份驗證時出現的警告的問題
       // String url = "jdbc:mysql://localhost:3306/test?" + "user=root&password=wsw011152&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
          String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
          String name = "root";
          String psw = "******";
          Connection connect = null;
    try {
        connect = DriverManager.getConnection(url, name, psw);
        // connect = DriverManager.getConnection(url);
        } catch (SQLException e) {
                // TODO Auto-generated catch block
          e.printStackTrace();
        }
      // 第三步: 創建一個 Statement ,一般建議使用 PreparedStatement
            // 1、執行靜態SQL語句。通常通過Statement實例實現。
            // 2、執行動態SQL語句。通常通過PreparedStatement實例實現。
            // 3、執行數據庫存儲過程。通常通過CallableStatement實例實現。
            // String sql = "select * from user where id = ?";
            String sql = "select * from user where id = ?";
    try {
         PreparedStatement ps = connect.prepareStatement(sql);
         ps.setInt(1, 1); // 設置參數
      // 第四步: 執行語句,獲得一個結果集,處理獲得的結果
         ResultSet result = ps.executeQuery();
          while (result.next()){            System.out.println(result.getInt("id"));
                    System.out.println(result.getString("name"));
                    System.out.println(result.getInt("age"));
                    System.out.println(result.getString("salary"));
          }
      // 第五步: 關閉資源
         result.close();
         ps.close();
         connect.close();
        } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
      }

JNDI配置使用:

  • 添加jar包
  • 在Tomcat/conf/context.xml中配置

  •  <Resource 
            name="jdbc/test" 
            auth="Container" 
            type="javax.sql.DataSource"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"
            username="root" 
            password="*****" 
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost:3306/test"
     />
  • 在項目web.xml文件中添加配置

  • <resource-ref>
          <description>DB Connection</description>
          <res-ref-name>jdbc/test</res-ref-name>
          <res-type>javax.sql.DataSource</res-type>
          <res-auth>Container</res-auth>
      </resource-ref>
  • 在代碼中連接、使用

  • DataSource ds = null;
    try {
      Context initContext = new InitialContext();
      DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/test");
      out.print(ds);
      } catch (Exception e) {
          e.printStackTrace();
      }
    connect = ds.getConnection();
    ....

總結:

JNDI通過在Tomcat服務器的配置文件和項目的web.xml上配置參數,可以靈活、快速地獲取數據庫配置信息並連接。對比JDBC,當數據庫參數、路徑等改變時也不需要改變代碼,比較靈活簡單。

JNDI和JDBC的區別及使用