<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 中的數據源 原文:http://zetcode.com/java/datasource/ 在本教程中,我們學習如何在 Java 中設置數據源。 我們使用 MySQL 數據庫系統。 ZetCode 擁有用于 MySQL Java 的完整電子書: [MySQL Java 編程電子書](/ebooks/mysqljava/)。 我們使用 MySQL Connector/J 驅動程序。 它是 MySQL 的官方 JDBC 驅動程序。 用 Java 創建到數據庫的連接有兩種基本方法:a)使用驅動程序管理器,b)使用數據源。 與驅動程序管理器相比,數據源具有幾個優點: * 它支持分布式事務 * 它提供了一種連接池技術 * 它可以由服務器(即應用外部)進行管理 當在 Java 類中創建和關閉連接時,驅動程序管理器會影響應用性能。 驅動程序管理器可用于簡單的測試應用中。 對于復雜的應用,始終建議使用數據源。 請參閱 [MySQL Java 教程](/db/mysqljava/),以了解如何在 Java 應用中使用驅動程序管理器。 通常,將基于 Java 命名和目錄接口(JNDI)API 向實現數據源接口的對象注冊命名服務。 ## JDBC JDBC 是 Java 編程語言的 API,用于定義客戶端如何訪問數據庫。 它提供了查詢和更新數據庫中數據的方法。 JDBC 面向關系數據庫。 從技術角度來看,API 是`java.sql`包中的一組類。 要將 JDBC 與特定數據庫一起使用,我們需要該數據庫的 JDBC 驅動程序。 ## MySQL MySQL 是領先的開源數據庫管理系統。 它是一個多用戶,多線程的數據庫管理系統。 MySQL 在網絡上特別流行。 MySQL 有兩個版本:MySQL 服務器系統和 MySQL 嵌入式系統。 ```java mysql> CREATE DATABASE testdb; Query OK, 1 row affected (0.02 sec) ``` 我們創建一個新的`testdb`數據庫。 在本教程中,我們只需要一個數據庫對象。 我們將不使用表格。 我們將使用`SELECT VERSION()`語句獲取 MySQL 數據庫的版本。 ## 命令行應用 在此示例中,我們使用命令行 Java 應用連接到數據庫。 ![Project structure](https://img.kancloud.cn/e5/a0/e5a0c03b618cd6d60bd8b5c50fe30010_408x199.jpg) 圖:項目結構 這就是 NetBeans 中項目結構的樣子。 `MysqlDataSource`是用于創建數據源的類。 `db.properties` ```java # mysql properties mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/testdb mysql.username=testuser mysql.password=test623 ``` 這些是 MySQL 數據庫的屬性。 `db.properties`文件位于此項目的`src/resources`子目錄中。 `ComLineDSEx.java` ```java package com.zetcode; import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; import java.util.Properties; public class ComLineDSEx { public static MysqlDataSource getMySQLDataSource() throws FileNotFoundException, IOException { Properties props = new Properties(); FileInputStream fis = null; MysqlDataSource ds = null; fis = new FileInputStream("src/resources/db.properties"); props.load(fis); ds = new MysqlConnectionPoolDataSource(); ds.setURL(props.getProperty("mysql.url")); ds.setUser(props.getProperty("mysql.username")); ds.setPassword(props.getProperty("mysql.password")); return ds; } public static void main(String[] args) throws IOException, SQLException { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; MysqlDataSource ds = getMySQLDataSource(); try { con = ds.getConnection(); pst = con.prepareStatement("SELECT VERSION()"); rs = pst.executeQuery(); if (rs.next()) { String version = rs.getString(1); System.out.println(version); } } finally { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } } } ``` 在此示例中,我們使用數據源連接到數據庫并獲取 MySQL 的版本。 ```java fis = new FileInputStream("src/main/Resources/db.properties"); props.load(fis); ``` 從具有`FileInputStream`類的`db.properties`文件中讀取數據庫屬性。 ```java ds = new MysqlConnectionPoolDataSource(); ds.setURL(props.getProperty("mysql.url")); ds.setUser(props.getProperty("mysql.username")); ds.setPassword(props.getProperty("mysql.password")); ``` 創建`MysqlConnectionPoolDataSource`并設置數據源屬性。 ```java con = ds.getConnection(); ``` 使用`getConnection()`方法從數據源創建連接對象。 ```java pst = con.prepareStatement("SELECT VERSION()"); ``` 創建一條 SQL 語句。 `SELECT VERSION()`命令返回 MySQL 的版本。 ```java rs = pst.executeQuery(); ``` 查詢被執行。 它返回一個結果集。 ```java if (rs.next()) { String version = rs.getString(1); System.out.println(version); } ``` 我們從結果集中獲取第一個值,并將其打印到控制臺。 ```java } finally { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } ``` 最后,資源被釋放。 ## Tomcat 中的 Web 應用 我們創建了一個 Web 應用,它將檢索 MySQL 的版本。 該應用已部署在 Tomcat 上。 ![Project libraries](https://img.kancloud.cn/04/a8/04a848830ca46c3de9f8bdc541ee2923_402x107.jpg) 圖:項目庫 在我們的項目中,我們使用 JSTL 和 MySQL 驅動程序 JAR。 JavaServer Pages 標準標記庫(JSTL) 是有用的 JSP 標記的集合,這些標記提供了許多 JSP 文件所共有的核心功能。 `context.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <Context path="/TomcatDSEx"> <Resource name="jdbc/testdb" auth="Container" type="javax.sql.DataSource" username="testuser" password="test623" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/testdb" maxActive="10" maxIdle="4"/> </Context> ``` 對于 Tomcat Web 服務器,我們在`context.xml`文件中創建一個新資源。 該文件位于`META-INF`目錄中。 `web.xml` ```java <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/testdb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app> ``` 然后,在`web.xml`文件中,創建對資源的引用。 在我們的應用中,我們將使用邏輯名稱`jdbc/testdb`引用數據源。 `index.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <c:redirect url="/Version"/> </body> </html> ``` `index.jsp`文件重定向到`Version` Servlet。 `showVersion.jsp` ```java <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>MySQL version</title> </head> <body> MySQL version: <c:out value="${version}"/> </body> </html> ``` `showVersion.jsp`是一個 UI 元素,用于顯示從數據庫檢索的數據。 ```java MySQL version: <c:out value="${version}"/> ``` JSTL 的`<c:out>`標記用于輸出響應的值。 `Version.java` ```java package com.zetcode.version; import com.zetcode.version.service.DBVersionService; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "Version", urlPatterns = {"/Version"}) public class Version extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String page = "/showVersion.jsp"; String version = DBVersionService.getMySQLVersion(); request.setAttribute("version", version); RequestDispatcher disp = getServletContext().getRequestDispatcher(page); disp.forward(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Returns version of MySQL"; } } ``` `Version` Servlet 調用服務方法來獲取 MySQL 的版本。 返回的值設置為請求對象的屬性。 ```java String page = "/showVersion.jsp"; ``` 最后,Servlet 指向`showVersion.jsp`文件。 ```java String version = DBVersionService.getMySQLVersion(); ``` 調用服務方法來獲取 MySQL 的版本。 ```java request.setAttribute("version", version); ``` 使用`setAttribute()`方法將版本值設置為請求對象。 ```java RequestDispatcher disp = getServletContext().getRequestDispatcher(page); disp.forward(request, response); ``` 我們調度到`showVersion.jsp`文件。 `DBVersionService.java` ```java package com.zetcode.version.service; import com.zetcode.version.Version; import com.zetcode.version.util.ServiceLocator; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.DataSource; public class DBVersionService { public static String getMySQLVersion() { String version = "no version"; DataSource ds = ServiceLocator.getDataSource("java:comp/env/jdbc/testdb"); Connection con = null; try { con = ds.getConnection(); Statement stm = con.createStatement(); ResultSet rs = stm.executeQuery("SELECT VERSION()"); if (rs.next()) { version = rs.getString(1); } } catch (SQLException ex) { Logger.getLogger(Version.class.getName()).log(Level.SEVERE, null, ex); } finally { if (con != null) { try { con.close(); } catch (SQLException ex) { Logger.getLogger(DBVersionService.class.getName()).log(Level.SEVERE, null, ex); } } } return version; } } ``` `DBVersionService`是一個服務類,其中包含獲取 MySQL 版本的方法。 ```java DataSource ds = ServiceLocator.getDataSource("java:comp/env/jdbc/testdb"); ``` 數據源是使用`ServiceLocator`類創建的。 ```java con = ds.getConnection(); Statement stm = con.createStatement(); ResultSet rs = stm.executeQuery("SELECT VERSION()"); if (rs.next()) { version = rs.getString(1); } ``` 在這里,我們有用于連接到數據庫并執行 SQL 語句的 JDBC 代碼。 `ServiceLocator.java` ```java package com.zetcode.version.util; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class ServiceLocator { public static DataSource getDataSource(String jndiName) { Context ctx = null; DataSource ds = null; try { ctx = new InitialContext(); ds = (DataSource) ctx.lookup(jndiName); } catch (NamingException ex) { Logger.getLogger(ServiceLocator.class.getName()).log(Level.SEVERE, null, ex); } return ds; } } ``` `ServiceLocator`通過其給定的 JNDI 名稱查找數據源,并將其返回給調用方。 ```java $ curl localhost:8084/TomcatDSEx/Version <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>MySQL version</title> </head> <body> MySQL version: 5.5.49-0ubuntu0.14.04.1 </body> </html> ``` 該應用將響應一個包含 MySQL 版本的 HTML 頁面。 這是 Java 教程中的數據源。 您可能也對 [JDBI 教程](/db/jdbi/), [MyBatis 教程](/db/mybatis/), [SQL 查詢標記教程](/java/sqlquerytag/)或 [MySQL 教程](/databases/mysqltutorial/)感興趣。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看